2013-03-30 56 views
5

我一直以为构造函数不能被继承,但是看看这个代码:Java构造函数继承?

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 

这表明,孩子继承的构造。为什么有S1结果?有没有可能创建2个没有参数的构造函数,只有Child构造函数的结果没有基础构造函数(只有S2)?

回答

1

Java的医生说:

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()。

1

构造函数不被继承。

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

是否有任何可能性创建2个没有参数的构造函数,并且没有基构造函数的结果上只有Child构造函数。

不,在Java中,每个派生类构造函数都调用超类构造函数。如果不添加它,则不调用任何参数构造函数。

public SuperClass() { 
    ... 
} 

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

你写:

这表明,孩子继承的构造。

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

这就是你得到这样的结果:

S1 
S2 
13

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

构造函数链通过继承的使用发生。子类 构造函数方法的第一个任务是调用其超类的构造函数 方法。这确保了在继承 链中创建子类对象时启动了 ,并且初始化了它上面的类。

继承链中可能有任何数量的类。构造函数的每个方法都会调用链,直到达到顶层 的类并初始化为止。然后下面的每个随后的类是 初始化,因为链回落到原来的子类。 (Source

这就是你的程序中发生的情况。当您编译的程序,你Childjavac编译成这样:

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

和您的父母类转换为以下几点:

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 
0

构造函数将始终调用其超类构造函数,除非已经定义了显式构造函数。从Java Language Specification

如果构造体不明确的构造函数调用,并正在申报的构造开始不是原始类对象的一部分,然后在构造函数体含蓄与超类构造函数调用“超级开始( );“,它的直接超类的构造函数的调用不带任何参数。