I have a question regarding casting of classes in runtime/compiletime.
class AA {
String s1 = "AA.s1";
String s2 = "AA.s2";
public int show() {
System.out.println("calling method in AA");
return 5;
}
}
class BB extends AA {
String s1 = "BB.s1";
public int show() {
System.out.println("calling method in BB");
return 10;
}
public static void main(String args[]) {
BB x = new BB();
AA y = (AA) x;
System.out.println(y.s1 + " " + y.s2 + y.show());
}
}
It prints the following answer:
calling method in BB
AA.s1 AA.s210
---------------------------
Here casting of x is done during compile time and hence the members of class, AA will be called. But howabout the method, show()? It calls the method in AA and the variables in BB. Just confused on why variables from superclass and methods from subclass.
Any help on explaining the situation would be highly appreciated.
Thanks.