尽管这是一个新手问题,但我对如何读取变量的值感到困惑?初始化时读取变量
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