Is there a way to access parent class instance variable with the same name as another child class instance variable through child reference outside child class?
class Parent {
int i;
}
class Child extends Parent {
int i=10;
}
class Test {
public static void main(String[] args) {
Parent p=new Parent();
Child c=new Child();
System.out.println(p.i);//parent i variable
System.out.println(c.i);//child i variable
System.out.println(c.i);// again child i variable
}
}
Cast the Child
to Parent
:
System.out.println(((Parent) c).i);
Why does it work?
A Child
instance has two fields named i
, one from the Parent
class and one from Child
, and the compiler (not the runtime type of the instance) decides which one gets used. The compiler does this based on the type he sees. So, if the compiler knows it's a Child
instance, he'll produce an accessor for the Child
field. If he only knows it's a Parent
, you get access to the Parent
field.
Some examples:
Parent parent = new Parent();
Child child = new Child();
Parent childAsParent = child;
System.out.println(parent.i); // parent value
System.out.println(child.i); // child value
System.out.println(((Parent) child) .i); // parent value by inline cast
System.out.println(childAsParent.i); // parent value by broader variable type
If the compiler knows it's a Child
, he gives access to the Child
field, if you take this knowledge away (by casting or by storing into a Parent
variable), you get access to the Parent
field.
This is confusing, isn't it? It's an invitation for all kinds of nasty misunderstandings and coding mistakes. So it's good advice not to have the same field name in a parent and a child class.