匿名内部类可以扩展吗?
我想创建一个扩展另一个类的匿名内部类。
我想要做的事实上是这样的:
for(final e:list){ Callable l = new MyCallable(ev) extends Callable(){ private e;//updated by constructor @Override public V call() throws Exception { if(e != null) return e; else{ //do something heavy } } }; FutureTask f = new FutureTask(l); futureLoadingtask.run(); } }
这可能吗?
你不能给你的匿名类命名,这就是为什么它被称为“匿名”。 我看到的唯一选择是从Callable
的外部范围引用final
变量
// Your outer loop for (;;) { // Create some final declaration of `e` final E e = ... Callable c = new Callable { // You can have class variables private String x; // This is the only way to implement constructor logic in anonymous classes: { // do something with e in the constructor x = e.toString(); } E call(){ if(e != null) return e; else { // long task here.... } } } }
另一种选择是对本地类(不是匿名类)进行范围调整,如下所示:
public void myMethod() { // ... class MyCallable implements Callable { public MyCallable(E e) { // Constructor } E call() { // Implementation... } } // Now you can use that "local" class (not anonymous) MyCallable my = new MyCallable ("abc"); // ... }
如果您需要更多,请创建一个常规的MyCallable
类…
extends关键字只允许在类定义中使用。 不允许匿名课程。
匿名类定义是: class没有任何名称,并且在声明后不使用。
我们必须更正您的代码(例如):
Callable test = new Callable () { @Override public String call() throws Exception { return "Hello World"; } };