简体   繁体   中英

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?

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)

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. And variable referring to J. If you want to use the super variable try super.x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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