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

Java静态内部类的应用

2016-03-07 10:10 323 查看
之前(http://blog.csdn.net/amazing_happens/article/details/50768748)讨论过静态内部类的使用方法,但是当真正遇到的时候,却反应不过来了。例如下面的例子:

import java.util.concurrent.*;

public class CallableTest {
public static class CallableAndFuture implements Callable<String>{
public String call()throws Exception{
return "Hello World";
}
}
public static void main(String[] args){
ExecutorService threadPool = Executors.newSingleThreadExecutor();
Future<String> future = threadPool.submit(new CallableAndFuture());
try {
System.out.println("waiting thread to finish");
System.out.println(future.get());
} catch (Exception e) {
e.printStackTrace();
}
}
}

CallableAndFuture这个类为什么变成了static类,去掉有没有异常?

果然,如果去掉static就会报一个错误:No enclosing instance of type CallableTest is accessible. Must qualify the allocation with an enclosing instance of type CallableTest (e.g. x.new A() where x is an instance of CallableTest).

at CallableTest.main(CallableTest.java:11)


这句话的意思是,由于CallableAndFuture是内部类,所以要想new一个CallableAndFuture实例,就必须先new一个CallableTest实例:

CallableTest  a = new CallableTest();
CallableAndFuture b = a.new CallableAndFuture();

当然还有一种更方便的方法,把CallableAndFuture类定义为静态类。

欢迎转载,但请注明出处。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: