super() in Java

前端 未结 15 2220
逝去的感伤
逝去的感伤 2020-11-22 05:36

Is super() used to call the parent constructor? Please explain super().

15条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 05:51

    Source article: Java: Calling super()


    Yes. super(...) will invoke the constructor of the super-class.

    Illustration:




    Stand alone example:

    class Animal {
        public Animal(String arg) {
            System.out.println("Constructing an animal: " + arg);
        }
    }
    
    class Dog extends Animal {
        public Dog() {
            super("From Dog constructor");
            System.out.println("Constructing a dog.");
        }
    }
    
    public class Test {
        public static void main(String[] a) {
            new Dog();
        }
    }
    

    Prints:

    Constructing an animal: From Dog constructor
    Constructing a dog.
    

提交回复
热议问题