我正在用 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/