【发布时间】:2015-09-14 09:02:43
【问题描述】:
如果我们在一个类中声明了一个私有实例变量,那么该变量只在该类内部可见,如果我们想访问它就必须为它创建成员函数,即该类的对象是无法直接访问... 例如,int 此代码...
class A {
private int a;
public int getA() {
return a;
}
}
class B extends A {
void display()
{
System.out.println(a);//error,trying to access private variable
A obj=new A();
System.out.println(obj.a); //Even object is not able to access it directly
System.out.println(obj.getA());//Fine,it can access
}
}
但是为什么在内部类的情况下,外部类的对象可以通过对象直接访问内部类的私有变量...例如-
class Outer {
void method1()
{
System.out.println(y); //Error,can't access private member of Inner
Inner obj=new Inner();
System.out.println(obj.y); //Why this doesn't show error
}
class Inner {
private int y;
}
}
为什么给java中的外部类提供这种权限???
【问题讨论】:
-
这两个代码块都不能编译;您在任何函数或方法之外都有
println语句。 -
是的,像这样的问题的出发点是编译的代码,并且在运行时,按照你说的做。
标签: java object inheritance nested private