简体   繁体   English

为什么在子类构造函数中调用“super()”?

[英]Why calling 'super()' in child class constructor?

Why do I need to call super here?为什么我需要在这里调用super

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.");
    }
}

If the parent constructor has no argument, no reason whatsoever.如果父构造函数没有参数,则没有任何理由。 Otherwise, you need an explicit call to super(...) where you can set those parameters.否则,您需要显式调用 super(...) 来设置这些参数。

By default every class having default constructor ie non parameterized constuctor, once you define any constructor on it then default behavour will not work.默认情况下,每个类都具有默认构造函数,即非参数化构造函数,一旦您在其上定义了任何构造函数,那么默认行为将不起作用。

Another thing is if any class extends any other class then by default each constructor of child class will call their parrent's default constructor ie super() internally but once you declare parameterized constuctor to the parent class then you need to call it from child class constructor explictly ie super(parameter...)另一件事是,如果任何类扩展任何其他类,那么默认情况下,子类的每个构造函数都会在内部调用其父类的默认构造函数,即 super() 但是一旦您向父类声明参数化构造函数,则需要从子类构造函数中显式调用它即超级(参数...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM