Java静态内部类的应用

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

import java.util.concurrent.*;

public class CallableTest {
	public static class CallableAndFuture implements Callable{
		public String call()throws Exception{
			return "Hello World";
		}
	}
	public static void main(String[] args){
		ExecutorService threadPool = Executors.newSingleThreadExecutor();
		Future 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类定义为静态类。


欢迎转载,但请注明出处。

你可能感兴趣的:(Java)