[英]When should the constructor of the superclass be called from the subclass?
The statement that calls the constructor of the superclass should be the last statement in the constructor of a subclass.
调用超类的构造函数的语句应该是子类的构造函数中的最后一条语句。
Is it a valid statement? 这是有效的声明吗?
No,that is not a valid statement.It MUST be the first statement of the child class's constructor. 不,那不是有效的语句。它必须是子类的构造函数的第一条语句。
If you don't add that line,the compiler will automatically add it. 如果您不添加该行,则编译器将自动添加它。
class A {
public A() {
System.out.println("Inside A's constructor.");
}
}
class B extends A {
public B() {
// super(); // THIS LINE WILL BE AUTOMATICALLY ADDED BY THE COMPILER.
System.out.println("Inside B's constructor.");
// super(); // THIS LINE WON'T COMPILE.
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
}
}
不,它应该是第一个语句...即使子类构造函数的第一行中没有默认构造函数,编译器也会隐式调用其父类的默认构造函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.