class init & object creation

3515 ワード

class init & object creation in inheritance
example:
execute SelfBall.java 's main() function,then get the result.
GrandpaBall.java

/**
 * grandpa ball
 * @author eric
 * @date 2010-3-19   11:43:42
 */
public class GrandpaBall {
	// static fields
	protected static int gx = gxInit();
	protected static int gy;
	// non-static fields
	protected int ga = gaInit();
	// static block
	static {
		System.out.println("grandpa static block init.");
	}
	// non-static block
	{
		System.out.println("grandpa non-static block init.");
	}

	// constructor
	public GrandpaBall() {
		System.out.println("grandpa constructor execute.");
	}

	private static int gxInit() {
		System.out.println("grandpa static field init.");
		return 1;
	}

	private int gaInit() {
		System.out.println("grandpa non-static field init.");
		return 1;
	}
}

FatherBall.java

/**
 * father ball
 * @author eric
 * @date 2010-3-19   11:44:01
 */
public class FatherBall extends GrandpaBall {
	// static fields
	protected static int fx = fxInit();
	protected static int fy;
	// non-static fields
	protected int fa = faInit();
	// static block
	static {
		System.out.println("father static block init.");
	}
	// non-static block
	{
		System.out.println("father non-static block init.");
	}

	// constructor
	public FatherBall() {
		System.out.println("father constructor execute.");
	}

	private static int fxInit() {
		System.out.println("father static field init.");
		return 2;
	}

	private int faInit() {
		System.out.println("father non-static field init.");
		return 2;
	}
}

SelfBall.java

/**
 * self ball,test class init & object creation
 * @author eric
 * @date 2010-3-19   11:44:19
 */
public class SelfBall extends FatherBall {
	// static fields
	protected static int sx = sxInit();
	protected static int sy;
	// non-static fields
	protected int sa = saInit();
	// static block
	static {
		System.out.println("self static block init.");
	}
	// non-static block
	{
		System.out.println("self non-static block init.");
	}

	// constructor
	public SelfBall() {
		System.out.println("self constructor execute.");
	}

	private static int sxInit() {
		System.out.println("self static field init.");
		return 3;
	}

	private int saInit() {
		System.out.println("self non-static field init.");
		return 3;
	}

	// main
	public static void main(String[] args) {
		System.out.println();
		System.out.println("executeing main() ... class has been loaded.");
		System.out.println("object is going to be created:");
		System.out.println();
		// create object
		SelfBall sb1 = new SelfBall();
		System.out.println();
		System.out.println("object created.");
	}
}