简体   繁体   English

继承类中的构造方法调用

[英]Constructor invocation in the inherited class

This is a very basic question on Java. 这是关于Java的一个非常基本的问题。 I've read somewhere that at first in the subclass's constructor the constructor of the super class is implicitly called. 我读过某个地方,起初在子类的构造函数中,隐式调用了超类的构造函数。 But I couldn't find the reference to the documentation, to read about that in detail. 但是我找不到对文档的引用,无法详细了解该文档。 Could someone please provide this reference? 有人可以提供此参考吗?

Here is an example of what I'm talking about, that outputs the super sub string: 这是我正在谈论的示例,该示例输出super sub字符串:

class SuperClass {
    static String s = "";
    protected SuperClass() { s += "super "; }
}

public class SubClass extends SuperClass {
    private SubClass() { s += "sub"; }
    public static void main(String[] args) {
        new SubClass();
        System.out.println(s);
    }
}

There's no overriding of constructors in Java - they're not called polymorphically to start with. Java中没有重载的构造函数-最初,它们不是多态调用的。

But each constructor has to call a constructor of the superclass, either implicitly (calling a parameterless one) or explicitly (with super(...) as the first line of the constructor body - or chain to another constructor within the same class, with this(...) as the first line of the constructor body. The chained constructor is executed before the rest of the constructor body. 但是,每个构造函数必须调用父类的构造函数,隐式(调用参数的一个)或明确地(用super(...)作为构造体的第一线-在同一个类中链另一个构造,与this(...)作为构造函数主体的第一行,链式构造函数在其余构造函数主体之前执行。

See section 8.8.7 of the Java Language Specification for more details. 有关更多详细信息,请参见Java语言规范的8.8.7节

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

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