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:
- You can't instantiate an abstract class (you can only instantiate sub-classes of that class).
- 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.