我有一个代码-
public class Hello
{
void create()
{
Inner obj=new Inner();
obj.r=100; //Able to access private variable x
obj.display(); //displays 100
}
class Inner
{
private int r=45;
void display()
{
System.out.println("r is : "+r);
}
}
public static void main(String[] args)
{
Hello ob=new Hello();
ob.create();
}
}
在上面的代码中,通过创建内部类的实例,我们可以访问该类中定义的私有(private)变量。但是继承的情况下却不是这样。为什么会这样?例如,在这个代码-
class One
{
private int x;
void getData()
{
x=10;
}
void display()
{
System.out.println("x is : "+x);
}
}
class Two extends One
{
int y;
void putData()
{
One o=new One();
o.x=13; //Error
}
}
public class File
{
public static void main(String[] args)
{
Two to=new Two();
to.putData();
}
}
其背后的确切原因是什么?提前致谢...
最佳答案
请参阅Java Language Specification .
Otherwise, if the member or constructor is declared
private
, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
这意味着顶级类可以访问其嵌套类的私有(private)成员。
或者换句话说:私有(private)意味着顶级类及其所有嵌套类私有(private),而不是嵌套类本身私有(private)。
关于java - 内部类变量的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32289331/