这是我写的一段代码。
public class cube {
private int length;
private int breadth;
private int height;
private int volume;
private int density;
private int weight;
public cube(int l,int b,int h, int d) {
length=l;
breadth=b;
height=h;
density=d;
}
public void volmeShow(){
volume = length * breadth * height;
System.out.println("The Volume of the cube is "+this.volume);
}
}
所以如果我像这样实现上面的立方体类,
public class cubeApp {
public static void main(String[] args){
cube mycube = new cube(5,6,9,2);
mycube.volumeShow();
}
}
我得到一个输出,告诉我音量是 270。
但我得到一个输出,说音量为 0。另一方面,如果我这样定义音量变量:
public class cube {
private int length;
private int breadth;
private int height;
private int volume=length*breadth*height;
private int density;
private int weight;
public cube(int l,int b,int h, int d) {
length=l;
breadth=b;
height=h;
density=d;
}
public void volmeShow(){
System.out.println("The Volume of the cube is " + this.volume);
}
}
为什么会这样?