2013-11-28 150 views
-1

正如我所知,构造函数,实例初始化块不会继承到子类,但下面的代码继承了超类构造函数,它为什么调用?Java:继承构造函数到子类

预计产量为:从利弊2

但它像显示输出: --IIB-- 从利弊1 从利弊2

WHY? this output , *As i know "sub class should not inherit Constructor & IIB block"* 

请帮我以澄清这个概念。

public class X 
{ 
    { 
     System.out.println("--IIB--"); 
    }  

    X() 
    { 
     System.out.println("from cons 1"); 
    } 
} 

class Y extends X 
{ 
    Y() 
    { 
     System.out.print("from cons 2"); 
    } 
}  


class Z 
{ 
    public static void main(String args[]) 
    { 
     Y ob=new Y(); 
    } 
} 
+1

如果构造函数体没有以显式构造函数调用开始,并且声明的构造函数不是原始类Object的一部分,则构造函数体隐式地以超类构造函数调用“super();”开始,它的直接超类的构造函数的调用没有任何参数。 http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.8 – Raghunandan

回答

6

发生这种情况,因为这样的:

Y() 
{ 
    System.out.print("from cons 2"); 
} 

实际上变成

Y() 
{ 
    super(); //Call to X's constructor made here even if you don't call it 
    System.out.print("from cons 2"); 
} 

这样做的原因是,每个Y也是X一个实例。在执行任何子构造函数之前,必须首先调用该父构造函数,以保证父属性已准备就绪。

编辑:这里的例子表明, “超级类的构造函数不是由子类inheriated”:

class A { 
    A(int intForA) { 
     //Do stuff... 
    } 
} 

class B extends A { 
    B() { 
     this(3); //Won't compile! A's constructor isn't inherited by B 
    } 
} 

相反,我们这样做:

class B extends A { 
    B() { 
     super(3); //This compiles; we're calling A's constructor from B 
    } 
} 
+0

你能告诉我一个例子,证明这个语句“超类构造函数没有被子类' – beginner

+0

现在有道理;添加了请求的示例。 –

2

当调用子类的构造函数,它internally calls the super class constructor using the super()(注意在链接上,在最后一节),并在你的情况下,Y超类是X。此外,实例块被复制到构造函数中,因此在调用该类的任何构造函数时执行。

init block docs

初始化语句块实例变量看起来就像静态初始化块,但没有static关键字:

{ 
    // whatever code is needed for initialization goes here 
} 

Java编译器副本初始化语句块到每一个构造函数。

因此输出按以下顺序。

--IIB-- - 从位于构造函数X内部的实例块。

from cons 1 - 当super()被称为内Y()

from cons 2 - 在你的代码Y extends X的SOP在Y()

1

因此,最好在创建Y类对象也创造X类对象。所以它的block首先被执行,然后是X的构造函数,然后是Y的构造函数。

因此,你正在得到这样的输出。