“public”或“protected”方法对于没有实现任何接口的私有嵌套类没有任何区别。?
如果私有嵌套类没有实现任何接口或从任何类继承,对于其方法的修饰符,它似乎是“公共”或“受保护”或没有修饰符没有任何区别。如果编译器仅允许它们“私有”,那将更有意义。所以 为什么java允许它们?
class Enclosing {
private class Inner {
private void f1() {}
void f2() {}
protected void f3() {}
public void f4() {}
}
void test() {
Inner o= new Inner();
o.f1();
o.f2();
o.f3();
o.f4();
}
}
答案 0 :(得分:2)
以下是我刚刚尝试的内容:
public class Test {
public void method(){
Innerclass ic = new Innerclass();
InnerClass2 ic2 = new InnerClass2();
System.out.println(ic.i);
System.out.println(ic.j);
System.out.println(ic.k);
System.out.println(ic.l);
System.out.println(ic2.i); // Compile Error
System.out.println(ic2.j);
System.out.println(ic2.k);
System.out.println(ic2.l);
}
private class Innerclass{
private int i;
public int j;
protected int k;
int l;
};
private class InnerClass2 extends Innerclass{
}
}
如上所述,这有一个错误。
答案 1 :(得分:0)
private
表示只能通过类范围访问。突然间,这条规则不适用于嵌套类。
除了private
之外,我没有定义任何其他类型的嵌套类。我希望从父类访问的成员是public
。