I was testing around with Java and noticed that casting "physically" changes properties of an object. I don't quite understand what actually happens inside Java when casting is used, but I did notice this:
Here is my Super class InstanceVariable
:
package inheritance;
public class InstanceVariable {
public int x = 1;
}
Here is a class that inherits from it:
package inheritance;
public class InstanceVariable1 extends InstanceVariable {
public int x = 100;
public static int y = 2;
public static void main(String[] args) {
InstanceVariable1 one = new InstanceVariable1();
InstanceVariable two = new InstanceVariable1();
System.out.println(one.x + " " + two.x);
one = (InstanceVariable) one; //This is illegal
}
}
First of all, the instance variable that were instantiated are overriden by the child class. And secondly, I can implicitly cast the super class (that is InstanceVariable
) to two
, but for some reason, I cannot explicitly cast it to one
? What is the reason for this?