I\'m having confusion in calling a non-static method
class A {
void doThis() {}
public static void main(String... arg) {
A
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.