2

Given myClass below and the non-static method run(), the following line of code is valid:

new myClass().move();

However, this is also valid:

move();

I understand the first attempt (new myClass().move()) creates an instance of the class and then calls the method on it. Does the second attempt also do the same thing but implicitly? In other words, are the 2 attempts really the same? If not, what is the fundamental difference and which one is preferred?

It seems OscarRyz's comment in the post here touched on this but he did not elaborate.

class myClass 
{
    void move() {
        //...some code
    }
    void run() {
        new myClass().move();
    }
}

Thanks.

Community
  • 1
  • 1
sedeh
  • 7,083
  • 6
  • 48
  • 65
  • 1
    Non-static methods _belong_ to an instance of the object (investigate "this" to learn more). Carefully consider which instance the method would consider to be "this" in your code. – Thorbjørn Ravn Andersen Nov 30 '14 at 14:01
  • See http://stackoverflow.com/questions/3728062/what-is-the-meaning-of-this-in-java – Bogdan Nov 30 '14 at 14:03

2 Answers2

2

They are not the same.

If you call move();, you execute the method on the current instance of myClass (this is the same as this.move();).

If you call new myClass().move();, you execute it on a new instance of myClass.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

It does not do the same thing.

With the first attemp new myClass().move(); you create another instance of your class and then call the method on this new instance.

But in your second attempt move(); you just call the method of your current instance. you already have initialized it. It's the same as this.move();

The second one is preferred, because you don't create another instance of your class but use the current one.

Ludovic Feltz
  • 11,416
  • 4
  • 47
  • 63
  • Thanks for also touching on the "preferred" method although what is preferred probably depends on the specific context. In the context of my code, I agree `this.move()` seems more efficient. – sedeh Nov 30 '14 at 14:21
  • @sedeh Sure it depends on the context but most of time if you can access the method in the current instance it's preferred than create a new instance of the class. – Ludovic Feltz Nov 30 '14 at 14:22