Is it better to call a method on a variable or cha

2019-09-19 15:27发布

问题:

There are examples of calling such methods on any class.

I.e.:

SampleClass sc=new SampleClass();
sc.someMethod();

Or is it better to use

new SampleClass().someMethod();

Please, explain in detail.

回答1:

Both options are as good, but first one is better...

If you use

SampleClass sc=new SampleClass();
sc.someMethod();

You can call other methods of this class using same object of class.

If you use

new SampleClass().someMethod();

You require another object to call other method of this class.


Other example is

loop { // Here loop can be any type, for/while/do-while
    new SampleClass().someMethod();
}

this will create objects of same class as many times your loop execute. But if you go with first option

SampleClass sc=new SampleClass();
loop { // Here loop can be any type, for/while/do-while
    sc.someMethod();
}

This will not cause to create many objects to call method.


But Yes, if your need is to call only one method and that is not into loop, you can go with new SampleClass().someMethod();



回答2:

Other than the obvious that sc remains an available variable in the first option that you can later call instance methods on, both are perfectly valid without additional context.

If you have a class method, (in Java terms, a static method), on the other hand, the object doesn't need constructed

SampleClass.someMethod();


回答3:

It depends. If you want to use anyother methods of SampleClass later, you might keep that variable (sc) alive in the instance. Otherwise,

new SampleClass().method();

is suffice.



回答4:

The first option allows you to access the object in the future again. You have a reference to it, so you will be able to invoke other methods of this object.

SampleClass sc = new SampleClass();
sc.someMethod();

and later:

sc.someOtherMethod();