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)


Man*_*shS 13

超类构造函数不能在扩展类中继承.虽然可以在扩展类构造函数中使用super()作为第一个语句来调用它.


小智 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()调用必须作为构造函数的第一行,否则编译器会对你生气.

  • 默认构造函数实际上不是"继承的".如果超类中存在公共无参数(AKA默认)构造函数,并且未在子类中显式定义,并且子类也没有任何显式定义的重载构造函数(即带参数的构造函数),则编译器将自动在子类中插入一个只包含`super();`的公共无参数构造函数.这会调用超类的默认构造函数. (2认同)