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

前端 未结 5 707
北荒
北荒 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:25

    Lets take a look at both these methods one by one.

    Method-1

    A a1 = new A();
    a1.doThis();
    

    In method-1, you have a reference of newly created instance of A, i.e a1 and you can call as many methods on this instance of A using this reference a1. Basically you can reuse that particular instance of A by using its reference a1.

    Method-2

    new A().doThis();
    

    However in method-2, you don't have any variable that stores the reference of your newly created instance of A. How will you refer to that particular instance of A if you have to call any other method on that particular instance of A ? You will not be able to re-use that instance of A if you create an instance using method-2 and you will lose that instance as soon as it is used.

提交回复
热议问题