Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

java - can anonymous inner classes extend?

I want to create an anonymous inner class that extends another class.

What I want to do is actually something like the following:

for(final e:list){

        Callable<V> l = new MyCallable(e.v) extends Callable<V>(){
              private e;//updated by constructor
                        @Override
                    public V call() throws Exception {
                        if(e != null) return e;
                        else{
                          //do something heavy
                        }

                    }               
        };
        FutureTask<V> f = new FutureTask<V>(l);     
        futureLoadingtask.run();
        }
}

Is this possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot give a name to your anonymous class, that's why it's called "anonymous". The only option I see is to reference a final variable from the outer scope of your Callable

// Your outer loop
for (;;) {

  // Create some final declaration of `e`
  final E e = ...
  Callable<E> c = new Callable<E> {

    // 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....
      }
    }
  }
}

Another option is to scope a local class (not anonymous class) like this:

public void myMethod() {
  // ...

  class MyCallable<E> implements Callable<E> {
    public MyCallable(E e) {
      // Constructor
    }

    E call() {
      // Implementation...
    }
  }

  // Now you can use that "local" class (not anonymous)
  MyCallable<String> my = new MyCallable<String>("abc");
  // ...
}

If you need more than that, create a regular MyCallable class...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...