1.内部类的定义与使用
No enclosing instance of type Outer is accessible. Must qualify the allocation with an enclosing instance of type Outer (e.g. x.new A() where x is an instance of Outer).
这个报错是说当前没有封闭的实例可以应用,即当前的内部类是动态的,不能直接实例化。
具体解决方法:https://blog.csdn.net/sunny2038/article/details/6926079/
即:---------------------------------------------------------------------------------------------------
public class Outer {
private int x = 1;
void sayHello(){
System.out.println("Hello!");
}
class Inner
{
int y = 0;
void test()
{
System.out.println(x);
sayHello();
}
}
}
public static void main(String args[])
{
Outer test = new Outer();
test.sayHello();
Outer.Inner in = new Outer.Inner();//这种定义方法错误,因为上面的Inner类是public类的(省略不写类型名,即认定为public类)
Outer.Inner in2 = test.new Inner();//这种方法可以,因为已经有了实例化的Outer类型test,可以通过test访问到Inner类
in.test();
in2.test();
}
2.内部类的三种使用方法
https://www.cnblogs.com/mayj/p/7027699.html
3.匿名内部类的示例
abstract class SayHello
{
public abstract void hello();
}
public class Test{
public void hello(SayHello sh){
sh.hello();
}
public static void main(String args[]){
Test t = new Test();
t.hello(new SayHello(){
public void hello()
{
System.out.println("Hello!");
}
});
}
}