我對繼承和對象創建感到困惑,我想了解下面的示例中完全構造了哪些對象。瞭解Java中的層次結構
class example
{
public static void main (String[] args)
{
System.out.println("starting...") ;
A localAinMain = new A() ; // object created
B localBinMain = new B() ; // object created
C localCinMain = new C() ; // object created
System.out.println("...finishing") ;
return ;
}
}
class A
{
// class fields
protected static int objectNo = 0 ;
private static C staticCinA = new C() ; // object created
// instance fields
public final int serialNo = ++objectNo ;
public A() { System.out.println("\tA.A[" + serialNo + "] - ctor\n") ; }
static { System.out.println("\tA - static initializer\n") ; }
}
class B extends A
{
// class fields
private static B staticBinB = new B() ; // object created
// instance fields
private A instanceAinB = new A() ; // object created
public B() { System.out.println("\tB.B[" + serialNo + "] - ctor\n") ; }
static { System.out.println("\tB - static initializer\n") ; }
}
class C extends B
{
// class fields
private static A staticAinC = new A() ; // object created
// instance fields
private B instanceBinC = new B() ; // object created
public C() { System.out.println("\tC.C[" + serialNo + "] - ctor\n") ; }
static { System.out.println("\tC - static initializer\n") ; }
}
當我運行這個程序,我得到下面的輸出
starting...
A.A[1] - ctor
A.A[2] - ctor
B.B[1] - ctor
B - static initializer
A.A[3] - ctor
C - static initializer
A.A[4] - ctor
A.A[5] - ctor
B.B[4] - ctor
A.A[6] - ctor
A.A[7] - ctor
B.B[6] - ctor
C.C[4] - ctor
A - static initializer
A.A[8] - ctor
A.A[9] - ctor
A.A[10] - ctor
B.B[9] - ctor
A.A[11] - ctor
A.A[12] - ctor
B.B[11] - ctor
A.A[13] - ctor
A.A[14] - ctor
B.B[13] - ctor
C.C[11] - ctor
...finishing
我想知道是否有人能解釋對象的創建順序像CC [11]和AA [11]將是「localCinMain 「,但我不理解爲什麼如此任何幫助表示讚賞