abk*_*srv 4 java inheritance inner-classes
恕我直言,我发现了一些模棱两可的东西。假设我们有以下类结构:
public class A
{
private int privateVar = 1;
protected int protectedVar = 2;
static class B extends A
{
public int getPrivateVariable()
{
return privateVar; //error: Cannot make a static reference to the non-static field memberVariable
}
public int getProtectedVariable()
{
return protectedVar; //OK: Why?
}
public int getPrivateUnfair()
{
return super.privateVar; //Why this can be accessed using super which the protected member doesn't require.
}
}
}
Run Code Online (Sandbox Code Playgroud)
protected和变量不同?private但是,如果嵌套类是非静态内部类,情况不是这样吗?super?
- 为什么静态嵌套类可以自由访问实例成员?
因为B extends A。您没有访问 的成员变量A,而是访问 的继承成员变量B。
- 为什么受保护变量和私有变量的访问方式不同?但是,如果嵌套类是非静态内部类,情况不是这样吗?
因为私有字段不能继承,而受保护字段可以;但私有字段仍然存在于超类中,并且通过super嵌套B可见A。可见性修饰符的表现力不足以阐明与通过 super 访问相同的内容。