Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm having confusion in calling a non-static method

class A {
    void doThis() {}

    public static void main(String... arg) {
        A a1 = new A();
        a1.doThis();        // method - 1
        new A().doThis();   // method - 2
    }
}

I know that both method-1 and method-2 will call doThis(), but is there any functional difference?

like image 788
Arun Sudhakaran Avatar asked Jan 17 '17 11:01

Arun Sudhakaran


3 Answers

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.

like image 79
Piotr Podraza Avatar answered Oct 13 '22 04:10

Piotr Podraza


Is there any functional difference?

Both will behave in the same way.

The second option doesn't allow you to reuse that instance again. It may be convenient and concise in one-line return statements (for instance, consider the builder pattern where each constructing method returns a half-initialised instance):

return new Builder().a().b().build();

or if an object was created only to perform a defined action once.

What will be the reference of a new object in method-2?

It is no longer exist (more precisely, we don't have access to it) unless the doThis returns this which you could be able to put in a variable after method execution.

Can I say that method-2 is an improper way of calling a non-static method?

No. Why should we create a variable if this variable will never be used afterwards?

like image 25
Andrew Tobilko Avatar answered Oct 13 '22 04:10

Andrew Tobilko


Let's see what the code says in plain English:

      A a1 = new A();
      a1.doThis();
  1. Create a new instance of A.
  2. Store a reference to it in the variable a1.
  3. Call doThis() on our instance.

Whereas new A().doThis(); reads as:

  1. Create a new instance of A.
  2. Call doThis() on our instance.

So the only difference is whether you store it in a local variable or not. If you don't use the value in the variable any more, then that difference doesn't matter. But if you want to call another method on the same object, let's say a1.doThat(), then you're in trouble with the second solution, as you haven't got a reference to the original instance any more.

Why would you want to use the same object? Because methods can change the internal state of the object, that's pretty much what being an object is about.

like image 28
biziclop Avatar answered Oct 13 '22 06:10

biziclop