java - 如何重用父类(super class)方法中的变量?

标签 java inheritance

我正在用 Java 创建一个完整的 Box 计算程序。实际上,如果宽度 = 5、高度 = 5、深度 = 5,则名为 volume 的变量的值应该为 125,但为什么无论 width 的任何值,输出显示的值都是 0 >、高度深度。我需要帮助......

下面是我的代码:

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

关于java - 如何重用父类(super class)方法中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55197219/

相关文章:

java - 如何在子类中使用泛型来限制方法参数类型?

Java标签语句和goto

java - 将自定义环境变量传递给 maven cargo

java - 在 RecyclerView 中显示 Firestore 集合的问题

c++ - 如何通过基类指针获取子类的属性

c++ - 在C++中,是否为派生类创建了一组新的私有(private)变量?

c# - 迭代器 block 和继承

c++ - 尽管在派生类中有定义,但基类中的方法不可见;多态性和使用 `virtual` 关键字

java - 写入时移动文件?

java - 使用 JPA 时如何允许 arrayList 中出现重复项?