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

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

最佳答案

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


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


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


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

关于java - 初始化时读取变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16256445/

10-10 16:54
查看更多