我们都知道,在开发中,有时不想写太多的代码,于是乎就用匿名的类不类,但有时我们的开发中要访问到匿名类不类的方法,当然,访问的方法有很多,但要是下面的一个例子呢?
public class Demo {
public static void main(String[]args){
//我想在这里调用Sy这个类
}
class Sy{
public void show(){
System.out.println("我是匿名类不类");
}
}
}
你可能会想,这还不简单,直接new 一下嘛,是真的吗??,你对这个对象一new就会出现No enclosing instance of type Demo is accessible. Must qualify the allocation with an enclosing instance of type Demo (e.g. x.new A() where x is an instance of Demo).就是说
没有任何类型演示的封闭实例是可访问的。必须用类型示例(例如x)来限定分配。新A(),其中x是演示的实例。
所以正确的做法是这种
public class Demo {
public static void main(String[]args){
new Demo().new Sy().show();;
}
class Sy{
public void show(){
System.out.println("我是匿名类不类");
}
}
}