分析解释代码BoxDemo3运行结果

分析解释运行结果中的line2,line4,line6,line7是如何得到的

/*
 * constructor, static
 */

class Box {
	double width;
	double height;
	double depth;
//    public static int number;
//	public final static int number;
	public static int instanceNumber=0;
 //  public final int instanceNumber;
	public final int number;
//	public int instanceNumber;
	
// This is the constructor for Box.
	Box() {
		System.out.println("Constructing Box");
		width = 10;
		height = 10;
		depth = 10;
		number = 1;
//		number++;
		instanceNumber++;
		System.out.println("The instanceNumber =" + instanceNumber);
	}

	// compute and return volume
	double volume() {
		return width * height * depth;
	}
}

class BoxDemo3 {
	public static void main(String args[]) {
		// declare, allocate and initialize Box objects
		Box mybox1 = new Box();	
		Box mybox2 = new Box();
		
		double vol;

		// get volume of the first box
		vol = mybox1.volume();
		System.out.println("Volume is " + vol);
		
		// get volume of the second box
//		vol = mybox2.volume();
		
//		System.out.println("Volume is " + vol);

		System.out.println("The number of Box objects is: " + mybox1.number);
		System.out.println("The number of Box objects is: " + mybox2.number);
		
	//	System.out.println("The number of Box objects is: " + mybox1.number);
		
//		System.out.println("The number of Box objects is: " + mybox1.instanceNumber);
		
	//	System.out.println("The number of Box objects is: " + mybox2.instanceNumber);
	}
}

在代码的第11行,我们发现instanceNumber初始值被定义为0:

	public static int instanceNumber=0;

在代码的第24行,我们发现Box每被调用一次,instanceNumber就会+1:

		instanceNumber++;
		System.out.println("The instanceNumber =" + instanceNumber);

而在代码的第37、38行,我们发现Box被以mybox1和2的形式调用了两次:

		Box mybox1 = new Box();	
		Box mybox2 = new Box();

所以在结果的line2,line4会依次打印输出:

The instanceNumber =1

The instanceNumber =2

在代码的第51、52行写有:

		System.out.println("The number of Box objects is: " + mybox1.number);
		System.out.println("The number of Box objects is: " + mybox2.number);

从第37、38行我们可以看到mybox1和2是新定义的Box

		Box mybox1 = new Box();	
		Box mybox2 = new Box();

而在代码的第13、22行,我们发现Box中的number的值恒等于1

	public final int number;
		number = 1;

所以结果的line6和line7显示为

The number of Box objects is: 1

The number of Box objects is: 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DoorBreaker

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值