Lin*_*ind 10 java inner-classes access-specifier
我正在阅读Java编程的介绍,它没有关于这个主题的很好的解释,它让我想知道为什么有人在java中使用私有内部类而不是使用公共内部类.
它们都只能由外层使用.
ami*_*mit 28
你的说法They both can be used only by the outer class.错了:
public class A {
private class B {}
public class C {}
public C getC() {
return new C();
}
public B getB() {
return new B();
}
}
public class Tryout {
public static void main(String[] args) {
A a = new A();
A.B b = a.getB(); //cannot compile
A.C c = a.getC(); //compiles perfectly
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,您实际上可以A.C在另一个类中拥有一个实例并将其引用为C(包括其所有公共声明),但不是A.B.
从中你可以理解,你应该使用私有/公共修饰符来内部类,就像你通常使用它一样.
| 归档时间: |
|
| 查看次数: |
9165 次 |
| 最近记录: |