And*_*are 48
构造函数不是继承的,您必须在子类中创建一个新的,相同原型的构造函数,该构造函数映射到超类中的匹配构造函数.
以下是一个如何工作的示例:
class Foo {
Foo(String str) { }
}
class Bar extends Foo {
Bar(String str) {
// Here I am explicitly calling the superclass
// constructor - since constructors are not inherited
// you must chain them like this.
super(str);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
默认构造函数 - 具有out参数(声明或隐含)的公共构造函数 - 默认继承.您可以尝试以下代码作为示例:
public class CtorTest {
public static void main(String[] args) {
final Sub sub = new Sub();
System.err.println("Finished.");
}
private static class Base {
public Base() {
System.err.println("In Base ctor");
}
}
private static class Sub extends Base {
public Sub() {
System.err.println("In Sub ctor");
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果要从超类中显式调用构造函数,则需要执行以下操作:
public class Ctor2Test {
public static void main(String[] args) {
final Sub sub = new Sub();
System.err.println("Finished.");
}
private static class Base {
public Base() {
System.err.println("In Base ctor");
}
public Base(final String toPrint) {
System.err.println("In Base ctor. To Print: " + toPrint);
}
}
private static class Sub extends Base {
public Sub() {
super("Hello World!");
System.err.println("In Sub ctor");
}
}
}
Run Code Online (Sandbox Code Playgroud)
唯一需要注意的是,super()调用必须作为构造函数的第一行,否则编译器会对你生气.