javainterfacefunctional-interface

Instance of object without implementing an interface


I have a code sample that defines a Worker interface and an Employee class that does not implement that interface. In my main method, I declare a Worker called w and instantiate it as an Employee.

This compiles and runs just fine, which confuses me. How is it possible to create a new Employee object as a Worker without implementing it?

public interface Worker {
    void work(double a);
}

public class Employee {
    public static void test() {
        System.out.println("Test");
    }

    public static void test(double a) {
        System.out.println("Number : " + a);
    }
}

public class MainClass {
    public static void main(String[] args) {
         Worker w = Employee::test;
         w.work(12);
    }
}

Solution

  • There are no instances of Employee created at all. You're using a method reference to implement the Worker interface, which is a functional interface due to only having a single abstract method.

    The Employee::test method reference (the overload accepting a double parameter) satisfies that functional interface, so the conversion from the method reference to the functional interface succeeds.