我的代码如下所示:
public class A<T extends A> {
private T one() { return (T) this;}
protected T two() { return (T) this;}
protected void three() { two().one(); }
}
而 IntelliJ 告诉我“one() 在 A 中具有私有(private)访问权限”,但是,为什么我不能调用同一类的私有(private)成员?
最佳答案
private
成员只能在声明它们的类中访问。所以如果你有课
class X{
private int field = 1;
private void method(){}
void foo(X x){
x.field = 2;
x.method(); // this is OK, because we are accessing members from instance of X
// via reference of class X (which is same class as this one)
}
void bar(Y y){// = lets assume that Y extends X
y.field = 3;
y.method(); // ERROR: we can't access `method()`
}
}
正如你所见,我们不允许从派生类访问私有(private)成员,即使我们在声明该成员的类中。
可能的原因是私有(private)成员没有被继承到派生类的接口(interface)(这是 private
可见性修饰符的全部目的)。因为在这样的类中,可以按照作者想要的任何方式重新声明这些成员,例如有人可以创建这样的类:
class Y extends X{
private String field = "foo";
private String method(){
return "bar";
}
}
如您所见,可以通过调用 y.method()
您正在尝试访问 method
在 Y
中声明类,但您无权从 X
访问它类(由于封装)。这是场景编译器假设的因为字段和私有(private)方法不是多态的。
为避免这种混淆,您需要明确声明您要使用强制转换从当前类 X 调用私有(private)成员
void bar(Y y){
((X)y).method();
}
同样的事情发生在 <T extends A>
.从 T
可以是 A
的任何子类编译器将不允许访问其私有(private)成员。因此,您需要将其转换回 A
class A<T extends A> {
private T one() { return (T) this;}
protected T two() { return (T) this;}
protected void three() { ((A)two()).one(); }
}
关于java - 为什么Java不允许我通过同一个类的方法访问私有(private)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30007480/