48

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.

public class Concrete<T> {
    // Has a bunch of predefined methods.
}


public abstract class Abstract<T> extends Concrete<T> {
    public T getSomething();
    // Uses inherited methods from Concrete class
}

public class Driver {
    public static void main(String[] args) {
        System.out.println(new Abstract<String>() {
            public String getSomething() {
                // Returns something using inherited methods from Abstract              
                // Class and Concrete Class
            }
        });
    }
}
2
  • 2
    in these kind of situations it would be helpful to include a MCVE where you have some super class, the abstract class and an instantiation that you would want to have reduced to a lambda expression
    – luk2302
    Commented Dec 22, 2015 at 21:11
  • Why can't you create an interface for getSomething() and have your abstract class extend Concrete and implement Interface?
    – Jan
    Commented Dec 22, 2015 at 21:21

4 Answers 4

58

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<T> extends Abstract<T>
{
    private final Supplier<? extends T> supplier;
    public AbstractLambda(Supplier<? extends T> supplier)
    {
        this.supplier = supplier;
    }

    @Override
    public T getSomething()
    {
        return this.supplier.get();
    }
}

This can be used with a lambda expression:

Abstract<String> 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();
2
  • 2
    I don't agree that Thread is defined in a similar way. A Runnable as a constructor argument to Thread is natural and Runnable simple FunctionalInterface. It don't look similar to this workaround.
    – snap
    Commented Feb 7, 2018 at 13:50
  • 4
    @snap They are similar. The only difference is that Thread is not abstract, but otherwise it's the same pattern: Either extend Thread and override run() or pass a Runnable to the Thread constructor. Commented Mar 29, 2019 at 19:13
46

No, You can't do it. Lambdas have to target single abstract method (SAM) on interfaces, and they don't work with single abstract method on abstract classes. This how it is, and you have to accept it,

Although it makes sense to have them, the language designers decided that it is not worth the complexity that will be introduced by allowing lambdas on SAM abstract classes.

As a reference, thats what Brian Goetz said about allowing lambdas on SAM abstract class.

Main key-points from Brian's email:

  • only 3% of the lambda candidate inner class instances had abstract classes as their target

  • Complicating the model for the sake of a few-percent-use-case seemed a bad trade

1
  • 1
    "This how it is, and you have to accept it". No. I won't accept it. I can't accept it.
    – user64141
    Commented Oct 17, 2021 at 4:30
1

As already pointed out, you can't.

But here another alternative that maybe usefull for somebody:

depending on your design, consider to use an interface with default functions instead of the abstract class:

This abstract class:

public abstract class RandomNumber {
    
    public abstract int createRandom(int smalles, int highest);

    public int rollTheDice() {
        return createRandom(1, 6);
    }

}

as an interface:

public interface RandomNumber {
    
    public int createRandom(int smalles, int highest);

    public default int rollTheDice() {
        return createRandom(1, 6);
    }

}

Now it is possible to write:

RandomNumber rn = (min, max) -> Math.random()*(max-min) + min;
0

In the meantime, we now have default implementations in interfaces. I was in a similar situation, tried with an abstract class. Switched to an interface with 2 methods, one of them having a default implementation. Java identifies the interface as having a single abstract method and I can use the lambda syntax for passing implementations of the interface as arguments.

The downside is that someone could override the method which has a default implementation if they really insist, by explicitly implementing the interface in some (anonymous or not) class. And you can't limit that because on interfaces all methods are public. Depending on your situation, that might not be a big deal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.