1

The constructor reference, which is a special type of method reference, when used for functional programming is evaluated without any explicit definition of abstract method declared in the Functional interface. Can you help me with the intricacies of how it's being resolved or linked? In particular to the following program how the empFactory object is evaluated?

public class Employee{
 String name;
 Integer age;
 public Employee(String name, Integer age){
  this.name=name;
  this.age=age;
 }
}

public interface EmployeeFactory{
 public abstract Employee getEmployee(String name, Integer age);
}


public class Run{
  public static void main(String... args){
  EmployeeFactory empFactory=Employee::new;
  Employee emp= empFactory.getEmployee("Ammy Sen", 25);
  }
}
  • `public abstract` is redundant on interfaces. Also is `interface` (lowercase) not `Interface` – Juan Carlos Mendoza Jan 17 '18 at 14:04
  • 1
    I don't understand your question, this is `method reference`, there is not a lot special going on here; it's just a form of it called `constructor reference`. You can replace `EmployeeFactory` with `BiFunction` btw – Eugene Jan 17 '18 at 14:08
  • That's certainly true, thanks @JuanCarlosMendoza – Suraj Mishra Jan 17 '18 at 14:08
  • 1
    No, `Employee::new` actually is `Employee::Employee` with signature (parameter types) `(String, Integer)`. – Joop Eggen Jan 17 '18 at 14:12
  • 1
    A constructor reference is less “dynamic” than a method reference to a non-`private` instance method. It’s entirely clear at compile-time, what will happen at runtime. – Holger Jan 17 '18 at 14:15

1 Answers1

7

Your method reference is equivalent to the lambda expression

EmployeeFactory empFactory = (name, age) -> new Employee(name, age);

In turn this is (more or less) the same as using an anonymous inner class implementing the EmployeeFactory interface:

EmployeeFactory empFactory = new EmployeeFactory() {
    @Override
    public Employee getEmployee(String name, int age) {
        return new Employee(name, age);
    }
};

So you can think of your empFactory being "an object that implements the EmployeeFactory interface, by implementing the single abstract method getEmployee(...) to return the result of calling the Employee constructor".

Also see Does a lambda expression create an object on the heap every time it's executed? for some differences between the implementation (but not the functionality) of the latter approach compared to the constructor reference.

James_D
  • 201,275
  • 16
  • 291
  • 322