Java静态方法中调用内部类
2017-11-13 08:04
260 查看
有时候我们在写一些外部接口程序的时候使用静态方法。在使用静态方法的时候,如果业务比较复杂需要用到内部类。
但是第一次我碰到了一个编译错误:
No enclosing instance of type Test(外部接口类) is accessible.
错误:
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).
解决:
在静态方法中初始化内部类需要先实例化外部类 然后再实例化内部类。
但是第一次我碰到了一个编译错误:
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();
相关文章推荐
- Java多线程运行时,尽可能调用单例对象、工具类和静态方法,这样可以减少内存的占用量
- freemarker调用java静态方法以及枚举
- java继承 父类子类方法调用问题 属性和静态方法是没有多态的
- java 类调用静态方法不需要实际对象存在吗,仅仅将类装载到内存中就可以了吗
- Java学习笔记——内部类及其调用方法
- Java中静态关键字的使用和内部类的调用
- Freemarker 调用Java静态方法
- java如何在主类方法调用内部类
- 入门: 使用JNI 从C++代码中调用Java的静态方法
- 分享一段JNI子线程中调用Java静态方法的代码
- java学习笔记(四)----对象、数组作为参数传递,静态变量、静态方法的使用,内部类,使用文档注释
- Java中静态关键字的使用和内部类的调用
- java 程序加载过程---3--类中申明同时申明类的静态对象 创建类的实例 访问类的静态变量 调用类的静态方法 使用反射方法 初始化类的子类对象 直接使用java.exe 调用某个类
- 【Java】内部类及其调用方法
- Struts2 OGNL表达式中调用java静态方法无效的解决办法
- Java中静态代码块,非静态代码块,以及父类与子类的构造方法的之间调用顺序
- Java 反射,调用类的静态方法
- Java Details-抽象的类可以调用其静态方法
- FreeMarker调用JAVA静态方法
- native 调用 java 类中的一个静态方法