【发布时间】:2010-11-15 10:03:30
【问题描述】:
我对下面展示的构造函数链接程序的输出有点怀疑:
class Cube {
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube() {
this(10, 10);
System.out.println("Finished with Default Constructor of Cube");
}
Cube(int l, int b) {
this(l, b, 10);
System.out.println("Finished with Parameterized Constructor having
2 params of Cube");
}
Cube(int l, int b, int h) {
length = l;
breadth = b;
height = h;
System.out.println("Finished with Parameterized Constructor having
3 params of Cube");
}
}
public class SpecialCube extends Cube {
int weight;
SpecialCube() {
super();
weight = 10;
}
SpecialCube(int l, int b) {
this(l, b, 10);
System.out.println("Finished with Parameterized Constructor having
2 params of SpecialCube");
}
SpecialCube(int l, int b, int h) {
super(l, b, h);
weight = 20;
System.out.println("Finished with Parameterized Constructor having
3 params of SpecialCube");
}
public static void main(String[] args) {
SpecialCube specialObj1 = new SpecialCube();
SpecialCube specialObj2 = new SpecialCube(10, 20);
System.out.println("Volume of SpecialCube1 is : "
+ specialObj1.getVolume());
System.out.println("Weight of SpecialCube1 is : "
+ specialObj1.weight);
System.out.println("Volume of SpecialCube2 is : "
+ specialObj2.getVolume());
System.out.println("Weight of SpecialCube2 is : "
+ specialObj2.weight);
}
}
输出:
Finished with Parameterized Constructor having 3 params of SpecialCube
Finished with Parameterized Constructor having 2 params of SpecialCube
Volume of SpecialCube1 is : 1000
Weight of SpecialCube1 is : 10
Volume of SpecialCube2 is : 2000
Weight of SpecialCube2 is : 20
疑问是关于如何实现“1000”、“10”、“2000”和“20”的输出?
在主类中我们创建了两个对象:
SpecialCube specialObj1 = new SpecialCube();
SpecialCube specialObj2 = new SpecialCube(10, 20);
第一个有“无参数”,第二个有“两个参数”,第一个“无参数”的构造函数 Cube() 只有两个值this(10,10),而一个有“两个参数”的有值
Cube(int l, int b)
{this(l, b, 10);}
我不明白下面的输出是如何生成的。
Volume of SpecialCube1 is : 1000
Weight of SpecialCube1 is : 10
Volume of SpecialCube2 is : 2000
Weight of SpecialCube2 is : 20
请谁能帮帮我!
谢谢, 大卫
【问题讨论】:
-
尝试调试代码,这是跟踪流程的最佳方式
-
操作似乎错误。应该首先打印 cube() 构造函数中的语句