Search code examples
javalambdainterfaceinterface-implementation

Why when I implement a lambda expression in the main method, the compiler doesn't say the interfaces are implemented?


When I implement interfaces as a Lambda expression in my main method, it doesn't count as if it was implemented.

I know I can implement it outside of the main method, but I don't see why I should use Lambda expressions if I have to implement it outside of the main anyway.

public class Driver implements Interface1, Interface2, Interface3 {

    public static void main(String[] args) {

        //Implementing Interface1
        double x;
        Interface1 obj = () -> 5.5;
        x = obj.foo();
        System.out.println(x);

        //Implementing Interface2
        String str;
        Interface2 obj2 = (a) -> String.format("The number is %d", a);
        str = obj2.foo(356);
        System.out.println(str);

        //Implementing Interface3

        boolean tF;
        Interface3 obj3 = (i, s) -> i == Integer.parseInt(s);


        tF = obj3.foo(30, "30");
        System.out.print(tF);

    }

Here, I get an error message at line 1 telling me that the Interfaces are not implemented. It still compiles and works, I just don't understand why I get this message. The output is currently:

5.5
The number is 356
true

Solution

  • All you have done is define local variables in the main method whose type happens to coincide with the interfaces that the class must implement.

    You must define methods in the class that provide implementations for all the interfaces of the class. For example:

    public class Driver implements Interface1, Interface2, Interface3 {
        public static void main(String[] args) {
            // all code in here is irrelevant to the class implementing Interface1, Interface2, Interface3
        }
    
        public void interface1Method() {
            // whatever
        }
    
        public void interface2Method() {
            // whatever
        }
    
        public void interface3Method() {
            // whatever
        }
    }
    

    Note that you can't use lambdas for this; Driver must actually declare implementations for the missing methods from all the interfaces its declares it is implementing.