Is there any functional difference?
Both will behave the same.
The second option does not allow you to reuse this instance again. This can be convenient and concise in single-line statements (for example, consider a builder pattern, where each construction method returns a semi-initialized instance):
return new Builder().a().b().build();
or if the object was created only to perform a specific action once.
What will be the reference to the new object in method-2?
It no longer exists (more precisely, we do not have access to it) if doThis
does not return this
, which you could add to the variable after the method is executed.
Is method-2 the wrong way to call a non-static method?
Not. Why should we create a variable if this variable will never be used later?
source share