2

I met in our project following code:

MyInterface var = MyClass::new;

Is there difference with

MyInterface var = new MyClass();

Lazy?

1
  • 2
    They don’t have anything in common. Commented Jun 4, 2015 at 10:19

1 Answer 1

9
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.

Sign up to request clarification or add additional context in comments.

8 Comments

Looks like you are wrong about these two constructs have nothing in common Single difference that I cannot cast second construction result to MyClass
The second construct does not require that 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.
second construction like: new MyInterface{ public MyClass{return new Myclass()}}
That isn’t valid Java code. But anyway, that’s a pointless discussion. A factory which creates X is something entirely different than an instance of X. That’s a fundamental difference and even if you could make X fulfill the same interface as the factory of X, that wouldn’t make that difference go away, just like foo() and bar() are different methods though you could make them do the same, they remain different.
So what? MyInterface var = new MyInterface(){ public MyClass anyMethodName(){ return new MyClass(); } } is also not the same as MyInterface var = new MyClass();
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.