继承与初始化和构造器的调用


调用构造器要遵循以下顺序:
1、调用基类构造器。这个步骤会不断反复递归下去,首先是构造这种层次结构的根,然后是下一层导出类,等等,直到最底层的导出类。
2、按声明顺序调用成员的初始化方法。
3、调用导出类构造器的主体。

继承与初始化
请看下例:

class Insect {
	private int i = 9;
	protected int j;// protected static int j; 上转型时 j 不再初始化,为39

	Insect() {
		System.out.println("i=" + i + ",j=" + j);
		j = 39;
	}

	private static int x1 = printInit("static Insect.x1 initialized");

	static int printInit(String s) {
		System.out.println(s);
		return 47;
	}
}

public class Beetle extends Insect {
	private int k = printInit("Beetle.k initialized");

	public Beetle() {
		System.out.println("k=" + k);
		System.out.println("j=" + j);
	}

	private static int x2 = printInit("static Insect.x2 initialized");

	public static void main(String[] args) {
		System.out.println("Beetle constructor");
		Beetle b = new Beetle();
		System.out.println();
		Insect a = new Beetle();
	}
}

运行结果:

static Insect.x1 initialized
static Insect.x2 initialized
Beetle constructor
i=9,j=0
Beetle.k initialized
k=47
j=39

i=9,j=0
Beetle.k initialized
k=47
j=39


构造器的调用顺序
请看下例:

class Meal {
	Meal() {
		System.out.println("Meal()");
	}
}

class Bread {
	Bread() {
		System.out.println("Bread()");
	}
}

class Cheese {
	Cheese() {
		System.out.println("Cheese()");
	}
}

class Lettuce {
	Lettuce() {
		System.out.println("Lettuce()");
	}
}

class Lunch extends Meal {
	Lunch() {
		System.out.println("Lunch()");
	}
}

class PortableLunch extends Lunch {
	PortableLunch() {
		System.out.println("PortableLunch()");
	}
}

public class Sandwich extends PortableLunch {

	private Bread b = new Bread();
	private Lettuce l = new Lettuce();
	private Cheese c = new Cheese();

	public Sandwich() {
		System.out.println("Sandwich()");
	}

	public static void main(String[] args) {
		new Sandwich();
	}
}

运行结果:

Meal()
Lunch()
PortableLunch()
Bread()
Lettuce()
Cheese()
Sandwich()




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值