I am setting up a simple example to show inheritance and polymorphism. I’m not sure how to explain the behavior I’m seeing in Android Studio debugger.
I have these two simple classes declared in an Empty View Activity project:
public class FirstClass {
public String whoAmI = "FirstClass";
int complexCalculation = 0;
public FirstClass(){
System.out.println("FirstClass Constructor");
complexCalculation = 3^6^8^9^3;
}
}
and
public class SecondClass extends FirstClass{
public String whoAmI = "SecondClass";
public SecondClass(){
System.out.println("SecondClass Constructor");
}
public void printWhoAmI(){
System.out.println(whoAmI);
}
}
And in the MainActivity:
SecondClass test = new SecondClass();
FirstClass tester= new FirstClass(); //What will be printed to log?
tester = test;
tester.whoAmI = "DoingStuff";
When placing a breakpoint on the last line and looking at the variables state, I see:

Why doesn’t the attribute itself change?
Where can I further read about the behavior displayed here?
>Solution :
Let’s boil down your example to the relevant part:
public class FirstClass {
public String whoAmI = "FirstClass";
}
public class SecondClass extends FirstClass{
public String whoAmI = "SecondClass";
}
Fields do not get overwritten. That means that instance of SecondClass actually contain 2 fields of the same name. To distinguish them, there is a way to address them, which is why they show up as whoAmI and FirstClass.whoAmI in your debugger.
With your testing setup essentially being
FirstClass tester = new SecondClass();
tester.whoAmI = "DoingStuff";
You created a reference to an object of type FirstClass that actually points to an instance of SecondClass. However unlike methods, fields do not use dynamic binding, which essentially makes java go "Oh, there’s actually a subclass in here. If you wanted to call a method, I would now invoke the subclass’s method. But it’s a field, so that mechanic is out of the picture. I will access the field of the type that this reference is declared as, which is FirstClass"
If you wanted to specifically change the subclass’s field, you would need either a cast:
((SecondClass)tester).whoAmI = ;
or a setter which the superclass defines and the subclass overrides.