can anonymous inner classes extend?

前端 未结 2 1525
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-20 09:29

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:lis         


        
相关标签:
2条回答
  • 2020-12-20 09:32

    extends keyword only allow using in class definition. Don't allow in anonymous class.

    Anonymous class define is: class without any name and don't use after declaration.

    We have to correct your code as following(for example):

    Callable<String> test = new Callable<String>()
    {
        @Override
        public String call() throws Exception
        {
            return "Hello World";
        }
    };
    
    0 讨论(0)
  • 2020-12-20 09:52

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

    0 讨论(0)
提交回复
热议问题