I was looking at this answer, and I don't understand the logic behind why methods would be polymorphic but not fields.
All member functions are polymorphic in Java by default. That means when you call this.toString() Java uses dynamic binding to resolve the call, calling the child version. When you access the member x, you access the member of your current scope (the father) because members are not polymorphic.
When you have some field x
in both the super and subclass, and override toString
in your subclass, when you call the following in the base class:
System.out.println(this); //calls the subclass's toString implementation
System.out.println(this.x) //prints the base class's x field
The justification for this in the answers listed in the question linked at the beginning is that the base class doesn't "know" about the subclass when it is in its own scope, but with polymorphism, it's the same thing: the superclass doesn't know the subclass exists, yet the subclass method is still called. So what exactly is Java doing that makes the two act differently - one using dynamic binding in the subclass and one keeping the scope of the superclass?
Edit: to clarify, I'm stuck on why this.x will do the same thing as polymorphism, look at the actual type of the object, not just the reference type, and print the x
field from the subclass.