Because variables in Java do not follow polymorphism and overriding is only applicable to methods but not to variables.
In Java, when the child and parent class both have a variable with the same name, Child class's variable hides the parent class's variable, even if their types are different. And this concept is known as Variable Hiding.
In the case of method overriding, overriding methods completely replaces the inherited methods but in variable hiding child class hides the inherited variables instead of replacing which basically means is that the object of Child class contains both variables but Child's variable hides Parent's variable. so when we try to access the variable within Child class, it will be accessed from the child class.
If we are trying to access the variable outside of Parent and Child class, then the instance variable is chosen from the reference type.
Why Instance Variable Is Chosen from Reference Type Instead Of Instance
As explained in How Does JVM Handle Method Overloading and Overriding Internally, at compile time overriding method calls are treated from the reference class only but all overridden methods get replaced by the overriding method at the runtime using a vtable and this phenomenon is called runtime polymorphism.
Similarly, at compile time variable access is also treated from the reference type but as we discussed variables do not follow overriding or runtime polymorphism, so they are not replaced by child class variables at the runtime and still refer to the reference type.
Why Variables do not Follow Overriding Or Why They Follow Hiding
Because variable overriding might break methods inherited from the parent if we change the variable's type in the child class.
We know every child class inherits variables and methods (state and behavior) from its parent class. Imagine if Java allows variable overriding and we change the type of a variable from int
to Object
in the child class. It will break any method which is using that variable and because the child has inherited those methods from the parent, the compiler will give errors in the child class.
And as mentioned, if Java allows variable overriding then Child's variable cannot substitute Parent's variable and this would break the Liskov Substitutability Principle (LSP).
You can read more on my articles What is Variable Shadowing and Hiding in Java, Why Instance Variable Of Super Class Is Not Overridden In Sub Class