您的位置:首页 > 编程语言 > Java开发

Java静态方法中调用内部类

2017-11-13 08:04 260 查看
有时候我们在写一些外部接口程序的时候使用静态方法。在使用静态方法的时候,如果业务比较复杂需要用到内部类。

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

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{

@Override
public 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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: