我正在用Java创建一个完整的Box计算程序。实际上,如果宽度= 5,高度= 5,深度= 5,则名为volume
的变量的值应为125,但为什么输出显示的值却为0,无论width
,height
和depth
的任何值如何。我需要帮助。
下面是我的代码:
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具有的所有属性。
眼镜蛇_8