如何在子类外部使用子引用访问与子变量同名的父类变量?

问题描述 投票:0回答:2

有没有办法通过子类外部的子引用来访问与另一个子类实例变量同名的父类实例变量?

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
    }
}
java inheritance super
2个回答
1
投票

Child
投射到
Parent
:

System.out.println(((Parent) c).i);

为什么有效?

Child
实例有两个名为
i
的字段,一个来自
Parent
类,一个来自
Child
,编译器(而不是实例的运行时类型)决定使用哪一个。编译器根据他看到的类型来执行此操作。因此,如果编译器知道它是一个
Child
实例,他将为
Child
字段生成一个访问器。如果他只知道这是
Parent
,您就可以访问
Parent
字段。

一些例子:

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

如果编译器知道它是

Child
,他就可以访问
Child
字段,如果您拿走这些知识(通过转换或存储到
Parent
变量中),您就可以访问
Parent
字段.

这很令人困惑,不是吗?这会引发各种令人讨厌的误解和编码错误。因此,最好不要在父类和子类中使用相同的字段名称。


1
投票

假设有充分的理由,那么是的:

class Child extends Parent {
    int i=10;

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

现在你的主要方法将如下所示:

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

编辑:意识到用户可能是新用户,所以我将充分充实方法签名并进行更多评论

© www.soinside.com 2019 - 2024. All rights reserved.