下面是我的代码:
public class TraditionalThreadSynchronized {
public static void main(String[] args) {
//OutPuter outPuter = new TraditionalThreadSynchronized ().new OutPuter(); //true
OutPuter outPuter = new OutPuter(); //false
new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outPuter.outPut("abcdefghjik");
}
}
}).start();
}
class OutPuter{
public void outPut(String name){
int len = name.length();
for(int i=0; i<len; i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
OutPuter 是一个普通的内部类,当我使用下面这个语句创建OutPuter 的实例对象是报错(No enclosing instance of type TraditionalThreadSynchronized is accessible. Must qualify the allocation with an enclosing instance of type TraditionalThreadSynchronized (e.g. x.new A() where x is an instance of TraditionalThreadSynchronized ).):
OutPuter outPuter = new OutPuter();
我在main方法中创建内部类的实例时出错,是因为普通的内部类是动态的(无static关键字修饰),而main方法是静态的,普通的内部类对象隐含地保存了一个引用,指向创建它的外围类对象,所以要在static方法(类加载时已经初始化)调用内部类的必须先创建外部类。即应该这样创建“OutPuter outPuter = new TraditionalThreadSynchronized().new OutPuter();”其中TraditionalThreadSynchronized 为外部类,OutPuter 为内部动态类;如果将内部内修改为静态类,可以在main中直接创建内部类实例。