天天看點

講講java類的執行個體化順序_Java類執行個體化的順序

package org.whb.test.demo805;

class A{

protected static String name = "jessie";

static{

System.out.println("static none name method of super(A) class");

}

{

System.out.println("none name method of super(A)");

}

public A(){

System.out.println("constructor of super(A)");

}

protected static void getName()

{

System.out.println(name);

}

protected static void setName(String pname)

{

name = pname;

System.out.println(name);

}

}

class B extends A{

static{

System.out.println("static none name method of sub(B) class");

}

{

System.out.println("none name method of sub(B) class");

}

public B(){

System.out.println("constructor sub(B)");

}

}

class C extends B{

public C(){

System.out.println("constructor of sub class(C)");

}

}

public class Test01{

public static void main(String[] ars)throws Exception{

A ab = new B();

System.out.println("**************************");

ab = new B();

System.out.println("**************************");

B BTest = new B();

System.out.println("**************************");

C CTest = new C();

System.out.println("**************************");

CTest.getName();

CTest.setName("shirley");

BTest.getName();

CTest.getName();

}

}

結果:

static none name method of super(A) classstatic none name method of sub(B) classnone name method of super(A)constructor of super(A)none name method of sub(B) classconstructor sub(B)**************************none name method of super(A)constructor of super(A)none name method of sub(B) classconstructor sub(B)**************************none name method of super(A)constructor of super(A)none name method of sub(B) classconstructor sub(B)**************************none name method of super(A)constructor of super(A)none name method of sub(B) classconstructor sub(B)constructor of sub class(C)**************************jessieshirleyshirleyshirley