【问题标题】:Class members vs object variables of subclass [duplicate]类成员与子类的对象变量[重复]
【发布时间】: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


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

    因为BoxWeight 定义了自己的lengthwidthheight,所以Box 中的对应字段被隐藏。您可以从BoxWeight 中删除字段,或转换为Box,如下所示:

    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
    

    【讨论】:

      【解决方案3】:

      这就是继承的工作方式。最后一个@Override 很重要。在这种情况下,它是BoxWeight

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多