I met in our project following code:
MyInterface var = MyClass::new;
Is there difference with
MyInterface var = new MyClass();
Lazy?
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.
MyClass implements MyInterface or that there is any relationship between MyInterface and MyClass. It is not different to Supplier<MyClass> s=MyClass::new;. As said, if MyClass implements MyInterface it may do it however it wishes and implementing it by letting MyClass constructing other MyClass instances would be very uncommon. The point is, just because you can make it equivalent using several special arrangements outside of these two statements, doesn’t make these two constructs themselves equivalent.foo() and bar() are different methods though you could make them do the same, they remain different.MyInterface var = new MyInterface(){ public MyClass anyMethodName(){ return new MyClass(); } } is also not the same as MyInterface var = new MyClass();