gstackoverflow
gstackoverflow

Reputation: 36984

Java constructor reference assignment Vs new created object assignment

I met in our project following code:

MyInterface var = MyClass::new;

Is there difference with

MyInterface var = new MyClass();

Lazy?

Upvotes: 2

Views: 342

Answers (1)

Holger
Holger

Reputation: 298233

MyInterface var = new MyClass();

creates an instance of MyClass and assigns it to a variable of type MyInterface. This requires that MyClass implements MyInterface and have a no-arg constructor. The result is an instance of MyClass which implements MyInterface however it likes to.


MyInterface var = MyClass::new;

attemps to implement MyInterface ad-hoc. This requires that MyInterface is a functional interface having a single abstract method. That single abstract method must have a return type assignable from MyClass and a parameter list matching one of MyClass’ constructors.

It is analog of:

MyInterface var = new MyInterface() {
    public MyClass anyMethodName() {
        return new MyClass();
    }
}

The result is an instance of MyInterface which will on invocations of its single abstract method create a new instance of MyClass passing all of its arguments to the constructor of MyClass.


In other words, these two constructs have nothing in common.

Upvotes: 9

Related Questions