여기에 제가 작성한 코드가 있습니다. 나는이 같은 위의 큐브를 구현한다면Java 변수 초기화
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
입니다하지만 볼륨이라는 출력을 얻을 수 반면에, 내가 이런 볼륨 변수를 정의한다면 :
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);
}
}
왜 이런 일이 일어나는 것입니까?
응답 주셔서 감사합니다.하지만 생성자가있는 클래스를 구현할 때 왜 이러한 변수 값이 변경되지 않는지 궁금합니다. 일단 내가 제공 한 값으로 새 '큐브'클래스를 생성하는 생성자를 구현하면, 왜이 새 클래스는 내가 제공 한 값에서 기본 변수 값으로 생성되지 않았는가, 왜 여전히 클래스의 초기화에서 값을 얻었는가? ? –
볼륨을 제외하고는 변수를 올바르게 초기화하고 있습니다. 따라서 '길이', '너비', '높이'및 '밀도'는 모두 올바르게 계산됩니다. 그러나'volume = length * breadth * height; '라는 계산은 변수가 초기화되기 전에 실행되므로'volume'이 0 인 이유 때문에'volume'이되지 않습니다. – jonny2k9
그것을 얻었습니다! 감사! –