Java静态方法中调用内部类

来源:互联网 发布:淘宝专享打折怎么设置 编辑:程序博客网 时间:2024/04/17 02:56

有时候我们在写一些外部接口程序的时候使用静态方法。在使用静态方法的时候,如果业务比较复杂需要用到内部类。

但是第一次我碰到了一个编译错误:

No enclosing instance of type Test(外部接口类) is accessible.

public class Test {public static void main(String[] args) {InnerClass inner = new InnerClass();}private class InnerClass implements Runnable{@Overridepublic void run() {}}}

//出错地方InnerClass inner = new InnerClass();

错误:

No enclosing instance of type Test is accessible. Must qualify the allocation with an enclosing instance of type Test (e.g. x.new A() where x is an instance of Test).


解决:

在静态方法中初始化内部类需要先实例化外部类 然后再实例化内部类。


//修正错误InnerClass inner = new Test().new InnerClass();



阅读全文
0 0