繁体   English   中英

如何重用超类方法中的变量?

[英]How can I reuse variable from super class method?

我正在用Java创建一个完整的Box计算程序。 实际上,如果width = 5,height = 5,depth = 5的话,名为volume的变量的值应为125,但为什么输出显示的值是0,而不管widthheightdepth任何值。 我需要帮助。

下面是我的代码:

import java.io.*;

public class Test {
    public static void main(String args[]) throws IOException {
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        Box obj1 = new Box();
        MatchBox obj2 = new MatchBox();

        System.out.print("Please Enter Width: ");
        obj1.width = Integer.parseInt(read.readLine());
        System.out.print("Please Enter Height: ");
        obj1.height = Integer.parseInt(read.readLine());
        System.out.print("Please Enter Depth: ");
        obj1.depth = Integer.parseInt(read.readLine());

        obj1.getVolume();
        obj2.displayVolume();
    }
}

class Box {
    int width, height, depth, volume;

    void getVolume() {
        volume = width * height * depth;
    }
}

class MatchBox extends Box {
    void displayVolume() {
        System.out.println("The Volume of Box is: " + volume);
    }
}

您创建一个名称为obj1的Box类的实例,并创建一个名称为obj2的MatchBox类的实例。 在此示例中,这不完全是您想要的!

代码如下所示:

...
MatchBox matchBox = new MatchBox(); ' you only need to create this instance

System.out.print("Please Enter Width: ");
matchBox.width = Integer.parseInt(read.readLine());
System.out.print("Please Enter Height: ");
matchBox.height = Integer.parseInt(read.readLine());
System.out.print("Please Enter Depth: ");
matchBox.depth = Integer.parseInt(read.readLine());

matchBox.getVolume();
matchBox.displayVolume();
...

这样,仅创建一个MatchBox的新实例,并且由于MatchBox是Box的子类,因此它也自动具有Box具有的所有属性。

Cobra_8

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM