简体   繁体   中英

How to access parent class variable having same name as child variable with child reference outside the child class?

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
    }
}

Assuming there's a good reason for it, then yes:

class Child extends Parent {
    int i=10;

    public int getParentsI() {
       return super.i;
    }
}

Now your main method will look like:

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.getParentsI());// parent i variable

Edit: realized the user may be new so I'll fully flesh out the method sig and comment more

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM