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

前端 未结 5 708
北荒
北荒 2020-12-11 05:54

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

class A {
    void doThis() {}

    public static void main(String... arg) {
        A          


        
5条回答
  •  遥遥无期
    2020-12-11 06:17

    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.

提交回复
热议问题