I\'m having confusion in calling a non-static method
class A {
void doThis() {}
public static void main(String... arg) {
A
Let's see what the code says in plain English:
A a1 = new A();
a1.doThis();
a1.doThis() on our instance.Whereas new A().doThis(); reads as:
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.