초보자 질문이지만 변수 값을 읽는 방법에 대해 혼란 스러웠습니다.초기화시 변수 읽기
int a = 7;
왼쪽이나 오른쪽으로 남겨 두겠습니까?
이 : X 그들의 슈퍼 클래스 인 경우
//X is a supper class of Y and Z which are sibblings.
public class RunTimeCastDemo {
public static void main(String args[]) {
X x = new X();
Y y = new Y();
Z z = new Z();
X xy = new Y(); // compiles ok (up the hierarchy)
X xz = new Z(); // compiles ok (up the hierarchy)
// Y yz = new Z(); incompatible type (siblings)
// Y y1 = new X(); X is not a Y
// Z z1 = new X(); X is not a Z
X x1 = y; // compiles ok (y is subclass of X)
X x2 = z; // compiles ok (z is subclass of X)
Y y1 = (Y) x; // compiles ok but produces runtime error
Z z1 = (Z) x; // compiles ok but produces runtime error
Y y2 = (Y) x1; // compiles and runs ok (x1 is type Y)
Z z2 = (Z) x2; // compiles and runs ok (x2 is type Z)
// Y y3 = (Y) z; inconvertible types (siblings)
// Z z3 = (Z) y; inconvertible types (siblings)
Object o = z;
Object o1 = (Y) o; // compiles ok but produces runtime error
}
}
내가 슈퍼 클래스는 = 새로운 서브 클래스가
X xy = new Y(); // compiles ok (up the hierarchy)
X xz = new Z(); // compiles ok (up the hierarchy)
읽기 방법하지 않는다 (왜, 계층까지의 것 ?) 아래쪽에 있지 않아야합니까?)
엄지 규칙은 항상 하위 유형 객체를 참조하기 위해 수퍼 유형 변수를 사용할 수 있다는 것입니다. –
어떻게 읽습니까? 두 가지 선택이 있습니다 : a = 7 또는 7 = a. Java에서는 원시 정수를 재 할당 할 수 없으므로 한 방향 만 이해할 수 있습니다. –
감사합니다 @DaveNewton하지만 변수에 대한 객체 할당을 처리하는 경우에는 어떻게해야합니까? 같은 일이 적용됩니까? EX : 수퍼 클래스 X = 서브 클래스 Y; X = 하위 클래스 Y 또는 Y = 수퍼 클래스 X로 읽을 수 있습니까? –