简体   繁体   English

JAVA继承问题-这与父类和子类之间的关系有关

[英]JAVA Inheritance issues- this is about the relationship between parent and child classes

So why is that I can cast a parent class as a child but not the other way around? 那么为什么我可以将家长班当成孩子,却不能相反呢?

When I set the object of a parent class to child and vice versa the properties are not copied why? 当我将父类的对象设置为child时,反之亦然,为什么不复制属性?

public class senior {
    private int a = 6;

    public int getA() {
        return a;
    }

    public int x = 1;
}

class junior extends senior {
    public junior() {
        super();
    }

    public int x = 0;
}

public class runner {
    public static void main(String[] args) {
        senior S = new senior();
        junior J = new junior();
        senior S1 = new senior();
        junior J1 = new junior();
        int b = J.getA();
        System.out.println(b);
        S = J; // aliasing ?
        // J 0 S 1
        System.out.println(S.x); // should print 0 but prints 1
        System.out.println(J.x);

        J1 = (junior) S1; // Senior cannot be cast to junior, why?
        System.out.println(S1.x);
        System.out.println(J1.x);// should print 1 but prints 0
    }
}

A Child class inherits all the methods and properties of all of its parent class. 子类继承其所有父类的所有方法和属性。 But the other way is not true since the child class is the one that extends the base class and the base class does not extend the child class. 但是另一种方法是不正确的,因为子类是扩展基类而基类不扩展子类的方法。 Hope it helped. 希望能有所帮助。

S = J; //aliasing ?

That is just assigning. 那只是分配。

//J 0 S 1
System.out.println (S.x); // should print 0 but prints 1

Variable bound to type. 变量绑定到类型。 Though the underlying object is j, the type is S (left side) 尽管基础对象是j,但类型是S(左侧)

J1 = (junior)S1; //Senior cannot be cast to junior, why?

Every Truck driver is Driver but you cannot say every Driver is a Truck Driver. 每个卡车司机都是司机,但您不能说每个司机都是卡车司机。

System.out.println (S1.x); 
System.out.println (J1.x);// should print 1 but prints 0

Variable bound to type. 变量绑定到类型。 object type is j. 对象类型是j。 And variable referring to J. If you want to use the super variable try super.x 并且变量引用J。如果要使用超级变量,请尝试super.x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM