Calling methods on reference variable vs Calling methods on a new object

There won’t be any difference in execution of those methods but in case of new A().doThis() your’re going to lose the reference to the instance of an object you’ve invoked the method on and you won’t be able to use it further in your code. All the changes this method could’ve done to internal state of the instance will be lost.

In case of A a1 = new A(); a1.doThis(); you’re going to preserve the instance of an object (in variable a1) and potential changes made to its state made by method doThis(). Then you’ll be able to continue working with this object.

Leave a Comment