【问题标题】:How to access parent class variable having same name as child variable with child reference outside the child class?如何使用子类外部的子引用访问与子变量同名的父类变量?
【发布时间】:2018-12-27 19:11:27
【问题描述】:

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

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

【问题讨论】:

  • 为什么需要这种方式?
  • 另外,这段代码有效吗?因为你实际上并没有说任何关于出错的事情,但是有一个代码......我假设你只是在问题中写了代码,并问我们这是否有效?
  • @krobelusmeetsyndra 代码有效。我想知道是否有任何方法可以通过子类外部的子类引用调用父类的实例变量 i。
  • @Deadpool。只是想知道是否有办法做到这一点。
  • @JoakimDanielson c.super.i 给出编译时错误

标签: java inheritance core super


【解决方案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 变量中),你就可以访问@987654336 @字段。

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

【讨论】:

    【解决方案2】:

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

    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
    

    编辑:意识到用户可能是新用户,所以我将完全充实方法 sig 并发表更多评论

    【讨论】:

    • 请缩进。
    • 很抱歉,我忘了提,有没有办法在不使用子类中的方法的情况下做到这一点我很抱歉我对这个网站很陌生,这个问题可能很愚蠢,但是在阅读有关使用超级关键字的信息时,我突然想到了谢谢
    • 不行,不使用子类方法是不行的
    猜你喜欢
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2012-07-04
    相关资源
    最近更新 更多