Java构造函数inheritance?

我一直以为构造函数不是inheritance的,但看看这段代码:

class Parent { Parent() { System.out.println("S1"); } } class Child extends Parent { Child(){ System.out.println("S2"); } } public class Test5 { public static void main(String[] args) { Child child = new Child(); } } //RESULT: //S1 //S2 

它表明Childinheritance了构造函数。 为什么结果有S1? 是否有可能创建没有参数的2个构造函数,并且在没有基础构造函数的结果中只有Child构造函数(只有S2)?

无论你在这里看到什么,都被称为构造函数链接 。 现在什么是构造函数链接:

构造函数链接通过使用inheritance来实现。 子类构造函数方法的第一个任务是调用其超类的构造函数方法。 这确保了子类对象的创建始于inheritance链中它上面的类的初始化。

inheritance链中可以有任意数量的类。 每个构造函数方法都会调用链,直到达到并初始化顶部的类。 然后,随着链回归到原始子类,下面的每个后续类都被初始化。 这个过程称为构造函数链接。( 来源 )

这就是你的程序中发生的事情。 编译程序时, javac以这种方式编译您的Child

 class Child extends Parent { Child() { super();//automatically inserted here in .class file of Child System.out.println("S2"); } } 

您的Parent类转换为以下内容:

 Parent() { super();//Constructor of Object class System.out.println("S1"); } 

这就是为什么你的输出显示为:

 S1 //output from constructor of super class Parent S2 //output from constructor of child Class Child 

Java doc说:

A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

如果未声明任何类型的构造函数,则会添加默认值。

如果不在子类的第一行调用任何其他构造函数,则调用super()。

构造函数不是inheritance的。

超类构造函数不在派生类中inheritance。

有没有可能创建没有参数的2个构造函数,并且在没有基础构造函数的结果上只有Child构造函数。

不,它不可能在Java中每个派生类构造函数都调用超类构造函数。 如果你不添加它,请调用无参数构造函数。

 public SuperClass() { ... } public DerivedClass() { //Compiler here call no argument constructor of Super class. } 

除非定义了显式构造函数,否则构造函数将始终调用其超类构造函数。 从Java语言规范 :

如果构造函数体不是以显式构造函数调用开始并且声明的构造函数不是原始类Object的一部分,那么构造函数体隐式地以超类构造函数调用“super();”开头,这是对构造函数的调用。它的直接超类不带参数。

你写:

它表明Childinheritance了构造函数。

构造函数不能被inheritance。 类可以inheritance,因此Child不会inheritance任何构造函数。 Childinheritance了Parent类。 父inheritance类Object。 当您调用子构造函数时,在运行子构造函数的代码之前,会自动调用Object构造函数,然后调用Parent构造函数。

这就是你得到这个结果的原因:

 S1 S2