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
}
}