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?
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:
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. If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With