I have couple questions regarding accessing public fields with inheritance. Considering below example.
public class SuperClass {
public int x;
// setter and getter methods for x
...
}
public class SubClass extends SuperClass {
public int x;
@Override
// setter and getter methods for x (both override superclass methods)
...
}
// inside main():
System.out.println("When using set method: ");
SubClass f = new SubClass();
f.setX(10);
((SuperClass) f).setX(100);
System.out.println("super: " + ((SuperClass)f).x);
System.out.println("subclass: " + f.x);
System.out.println("\nWhen changing field directly:");
f.x = 10;
((SuperClass) f).x = 100;
System.out.println("super: " + ((SuperClass)f).x);
System.out.println("subclass: " + f.x);
which prints out as:
When using set method: // why are the variable values swapped?
super: 10
subclass: 100
When changing field directly: // these results are within expectation
super: 100
subclass: 10
I thought that casting will only affect how compilers treat the object, and during execution time object will access its fields and methods based on how the object is initialized without consider what type/class it is.
However I feel my understanding towards this subject might be incomplete or plainly wrong.
Question 1: In the first case scenario (using set method), why does the result looks like that? More specifically, I want to know how does setting and invoking public fields directly work, and when is this done (execution time or compiler time)?
Question 2: where/how is super class's hidden fields stored? I'm asking this because it looks like superclass's fields are stored seperately from the subclass, even though they should be the same by using just casting. Since the compiler allocated memory for just a single normal subclass object, I don't see how there's extra space to store superclass's information.
The situation is more confusing when declared object f as Superclass but instantiated as Subclass.
I'm running this on JDK 11.0.2