【发布时间】:2015-04-14 12:23:33
【问题描述】:
下面是代码 sn-p 及其输出 -
class Box{
int height = 1;
int length = 1;
int width = 1;
Box(int h, int l, int w){
this.height = h;
this.length = l;
this.width = w;
}
int volume(){
return this.height * this.length * this.width;
}
}
class BoxWeight extends Box{
int height = 99;
int length = 99;
int width = 99;
int mass;
BoxWeight(int h, int l, int w, int m) {
super(h, l, w);
this.mass = m;
}
int volume(){
return this.height * this.length * this.width;
}
}
public class BoxDemo {
public static void main(String[] args) {
Box b = new Box(10, 20, 30);
BoxWeight bw = new BoxWeight(40, 50, 60, 10);
System.out.println(bw.height);
System.out.println(bw.length);
System.out.println(bw.width);
//b = bw;
//System.out.println(b.volume());
}
}
输出
99
99
99
在这里我无法理解为什么对象 bw 正在打印初始化为类成员的值。为什么对象 bw 不保存通过构造函数分配的值?
【问题讨论】:
-
实际上最终目的不是打印 40, 50, 60 ,我只是想知道这里的幕后发生了什么。如果有人可以在这里放一些关于此的好读物,那可能会有所帮助。哪种 java 机制在这里工作?
-
当在 BoxWeight 构造函数中 ""BoxWeight(40, 50, 60, 10)** 被调用,它再次调用 super 来初始化高度、宽度、长度我认为所有的初始化在 this 上使用 super 表示 BoxWeight 对象的值依次为 40、50、60。
标签: java