Lambda Expressions for Abstract Classes

后端 未结 3 1439
梦如初夏
梦如初夏 2020-11-30 03:03

I have an abstract class with one abstract method. How can I use lambda expressions to instantiate it. It cannot be made into an interface because it extends a class.

3条回答
  •  遥遥无期
    2020-11-30 03:42

    You cannot directly make a lambda expression target an abstract class, as Sleiman Jneidi pointed out in his answer. However, you can use a workaround:

    public class AbstractLambda extends Abstract
    {
        private final Supplier supplier;
        public AbstractLambda(Supplier supplier)
        {
            this.supplier = supplier;
        }
    
        @Override
        public T getSomething()
        {
            return this.supplier.get();
        }
    }
    

    This can be used with a lambda expression:

    Abstract a = new AbstractLambda<>(() -> "Hello World");
    System.out.println(a.getSomething()); // prints 'Hello World'
    

    In case your getSomething(...) method has arguments, use a java.util.function.Function or the appropriate interface from the java.util.function package instead of java.util.function.Supplier.


    This is also how the java.lang.Thread lets you use a Runnable lambda instead of having to subclass the class:

    Thread t = new Thread(() -> System.out.println("Hello World"));
    t.start();
    

提交回复
热议问题