Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 lambda expression with an abstract class having only one method [duplicate]

I'm learning lambda expressions in Java 8. Can somebody explain to me how to use lambda expression with an abstract class having only one method (if it's possible)?

For example, this is the abstract class:

public abstract class ClassA {

    public abstract void action();

}

And I have another class that take's in its constructor an instance of ClassA:

public ClassB {
   public ClassB(String text, ClassA a){
      //Do stuff
    }
}

So I was wondering how to write something like this:

ClassB b = new ClassB("Example", new ClassA(() -> System.out.println("Hello")));

Obviously that statement doesn't work, but is there a way to use a lambda expression here or not? If there is, what am I doing wrong?

like image 255
navy1978 Avatar asked Dec 18 '17 18:12

navy1978


1 Answers

You can only instantiate a functional interface with a lambda expression.

For example:

If you change ClassA to be an interface (you'd probably want to rename it):

public interface ClassA {
    public abstract void action();
}

and keep ClassB as is:

public class ClassB {
   public ClassB(String text, ClassA a){
      //Do stuff
    }
}

You can pass an instance of (the interface) ClassA to the ClassB constructor with:

ClassB b = new ClassB("Example", () -> System.out.println("Hello"));    

On the other hand, your

ClassB b = new ClassB("Example", new ClassA(() -> System.out.println("Hello")));

attempt fails due to several reasons:

  1. You can't instantiate an abstract class (you can only instantiate sub-classes of that class).
  2. Even if you could instantiate class ClassA (if it wasn't abstract), your ClassA has no constructor that takes some functional interface as an argument, so you can't pass () -> System.out.println("Hello") as an argument to ClassA's constructor.
like image 70
Eran Avatar answered Oct 26 '22 03:10

Eran