https://bbs.csdn.net/topics/60085298
问题
不明白什么时候适合使用静态内部类?书上说是在内部类没有对外部类的引用时,可以去掉对外部类的引用,仅仅是为了这个原因吗,去掉引用对效率提高很有帮助吗?
回答
static内部类意味着:
(1) 为创建一个static内部类的对象,我们不需要一个外部类对象。
(2) 不能从static内部类的一个对象中访问一个外部类对象.
倘若为了创建内部类的对象而不需要创建外部类的一个对象,**也就是内部类中不需要访问外部类中的属性和方法**
,那么可将所有东西都设为 static。为了能正常工作,同时也必须将内部类设为static。
此外,也可考虑用一个static内部类容纳自己的测试代码。
如下所示:
class TestBed {
TestBed() {}
void f() { System.out.println("f()"); }
public static class Tester {
public static void main(String[] args) {
TestBed t = new TestBed();
t.f();
}
}
}