0
我有一个代码 -能见度内部类变量的
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();
}
}
在上面的代码中,通过创建内部类的实例,我们能够访问该class.But这是所定义的专用变量不inheritance.Why的情况下,它是这样的吗?对于例如,在这个代码 - 提前
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中,public,default,protected和private之间的区别是什么?](http://stackoverflow.com/questions/215497/in-java-whats-the-difference-between-public -default-protected-and-private) – Mephy
很难想象除**以外的答案,因为**这就是Java的实现方式。 –
使用'protected'有什么问题?应该在两种情况下工作。 – puelo