I'm learning anonymous inner classes and lambda functions in Java, especially polymorphism and "passing" interfaces and classes (which apparently means passing an object reference to them, which I'm trying to show below).
I'd like to make the change that my IntelliJ IDEA IDE suggests at poly3 where it says, "Anonymous new Foo() can be replaced with lambda." How do I complete that?
package org.example;
interface Foo {
String foo();
}
public class Bar implements Foo {
@Override
public String foo() {
return "hi";
}
public static void main(String[] args) {
Object poly1 = new Bar();
Foo poly2 = new Bar();
Object poly3 = new Foo() { public String foo() { return "hi"; }}; // Anonymous new Foo() can be replaced with lambda
Object poly4 = () -> { return "hi"; }; // Error: Target type of a lambda conversion must be an interface
}
}
When using lambda you need a FunctionalInterface.
java.lang.Objectis not such - it does not have abstract methods. You need to either declare the variable to beFooor you need to cast your lambda to
Foo