Java 类成员与子类的对象变量

Java 类成员与子类的对象变量,java,Java,下面是代码片段及其输出- 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

下面是代码片段及其输出-

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没有保存通过构造函数分配的值?

BoxWeight的成员隐藏了Box的成员,因此您看不到传递给Box构造函数的值

只需从
BoxWeight
中删除此成员即可:

        int height = 99;
        int length = 99;
        int width = 99;

在两个类中使用完全相同的
volume()
实现也是没有意义的。

继承就是这样工作的。最后的
@覆盖
计数。在这种情况下,它是
BoxWeight

,因为
BoxWeight
定义了它自己的
长度
宽度
、和
高度
,所以
框中的相应字段被隐藏。您可以从
BoxWeight
中删除字段,或按如下方式转换到
框中:

public static void main(String[] args) {
    Box b = new Box(10, 20, 30);
    BoxWeight bw = new BoxWeight(40, 50, 60, 10);
    System.out.println(((Box) bw).height);
    System.out.println(((Box) bw).length);
    System.out.println(((Box) bw).width);
}
印刷品:

40
50
60

实际上,最终的目标不是打印40、50、60,我只是想知道幕后发生了什么。如果有人能在这里发表一些关于这方面的好文章,这会很有帮助。哪个java机制在这里工作?当在BoxWeight构造函数中调用“BoxWeight(40,50,60,10)**时,它再次调用super来初始化高度,宽度,长度。我认为所有使用super的初始化都将在这意味着BoxWeight对象上完成,而BoxWeight对象的值将依次为40,50,60。