访问 child class 中的私有实例

Accessing private instances in child class

我已经在 Stack Overflow 上看到了与我的问题相关的答案,但我仍然有一些不明确的地方。 parent class 方法可以访问它自己的私有实例变量。如果 child class 继承了 class,当 getA() 方法在 Child class 的实例上调用时会发生什么? return Parent class 中的 a 还是 Child class 中的 a

class Parent {
    private int a = 10;  
    public int getA() {
       return a;
    }
 }

class Child extends Parent {
    private int a = 22;              
 }

public class Test { 
   public static void main(String []args) throws Exception {        
       Child c = new Child(); 
       System.out.println(c.getA());
   }    
}

这是 this SO post 的副本。

子class中的变量a Child隐藏了父class中的a Parent.

无法覆盖字段。

在您的代码中,child 的一个实例(如 c 所指的那个)有 两个不同的字段,它们都称为 a .

您无法在 Child 中访问 Parent 的私有变量,句号。这就是 private 的全部要点。没有什么*你可以在 Child 里面写来使父级的 a 字段等于 22.




* 从技术上讲,你可以反思。不过,反射不算数,因为它的目的本质上是让你打破事物,并做一些否则不可能的事情。

私有变量是 class 的局部变量,在您的代码中您继承了父级 class 的属性,因此您可以访问 getA() 并且它将 return 父级的属性。 除非你有子属性的 public getter 方法,否则你无法访问子变量。

由于方法 getA() 是继承的,如果您调用此方法,您将始终调用 Parent 的方法。

当前对象将被视为 Parent 而不是 Child,并且 Parent 的 a 将被 returned。

即使您有自己的变量 a,此变量也不会覆盖 Parenta。它们彼此不同,具有不同的地址和不同的值。

如果您想要 getA() 到 return Childa,您需要将方法重写为 return 您的新变量。

class Child extends Parent {
    private int a = 22;

    @Override
    public int getA(){
        return a;
    }
 }

您也可以 "go crazy" 并执行以下操作:

class Child extends Parent {
    private int a = 22;       

    @Override
    public int getA(){
        int superA = super.getA();

        return a+superA;    
    }
 }

这样你就可以 return ParentChilda.

的总和

(举个例子)

坚持基础知识 "private member variable will only be accessed within the class by its own member functions and fields cannot be inherited" 所以基本上当您访问父级 class 中的私有变量 A 时,该方法应该访问它自己的私有成员而不是任何子级的私有字段 class。