The question is published on by Tutorial Guruji team.
I’m wondering why Java has this strange behavior regarding a superclass and a subclass having instance variables with the same name.
Let’s say we have the following class definitions:
class Parent { int var = 1; } class Child extends Parent { int var = 2; }
By doing this, we are supposed to have hidden the superclass’s variable var
. And if we do not explicitly specify a way to access Parent
‘s var
via a super
call, then we should never be able to access var
from an instance of a child.
But when we have a cast, this hiding mechanism breaks:
Child child = new Child(); Parent parent = (Parent)child; System.out.println(parent.var); // prints out 1, instead of 2
Doesn’t this completely circumvent the whole point of field hiding? If this is the case, then doesn’t that render the the idea completely useless?
EDIT: I am referring specifically to this article in the Java Tutorials. It mentions
Within the subclass, the field in the superclass cannot be referenced by its simple name. Instead, the field must be accessed through super…
From what I read there, it seems to imply that the developers of Java had some kind of technique in mind in doing this. Though I agree that it is a rather obscure concept and would probably bad practice in general.
Answer
In Java, data members are not polymorphic. This means that Parent.var
and Child.var
are two distinct variables that happen to have the same name. You’re not in any sense “overriding” var
in the derived class; as you have discovered yourself, both variables can be accessed independently of one another.
The best way forward really depends on what you’re trying to achieve:
- If
Parent.var
should not be visible toChild
, make itprivate
. - If
Parent.var
andChild.var
are two logically distinct variables, give them different names to avoid confusion. - If
Parent.var
andChild.var
are logically the same variable, then use one data member for them.