在初始化时读取变量

时间:2013-04-27 20:12:09

标签: java

虽然这是一个新手问题,但我对如何读取变量的值感到困惑?

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是它们的超类,为什么它会在层次结构中上升?它应该不会失效吗?)

1 个答案:

答案 0 :(得分:2)

  

......如何读取变量的值?

对于=(赋值)操作,将评估右侧的值并将其存储到左侧的变量中。因此,在您的示例中,首先评估7并将其存储到a中。如果右侧更复杂,则会在存储到左侧变量之前从左到右进行评估。

  

如果X是它们的超类,为什么它会在层次结构中出现?它不应该失效吗?

允许将子类存储为其超类,因为子类实现了超类的所有功能。因此,如果X定义方法Test(),而YX的子类,那么Y也会实现该方法。因此,您可以拥有Y的实例,并将其存储在X类型的变量中,因为X中的所有Y功能都可用。

相关问题