儘管這是一個新手問題,但我對如何讀取變量的值感到困惑?初始化時讀取變量
int a = 7;
它會從左到右還是從右到左?
也這樣:
//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)
(它爲什麼會成爲了層次,如果X是他們的超?它應該不會下降嗎?)
拇指規則是您始終可以使用超類型變量來引用子類型對象。 – 2013-04-27 20:14:28
它是如何讀取的?你有兩種選擇:a = 7或者7 = a。在Java中,你不能重新分配一個原始整數,所以只有一種方法有意義,不是嗎? – 2013-04-27 20:20:21
謝謝@DaveNewton但如果你正在處理變量的對象賦值?做同樣的事情嗎? EX: 超類X =子類Y; 是否可以讀取爲X =子類Y 或Y =超類X? – 2013-04-27 20:24:16