Is it better to call a method on a variable or bind it to a constructor?

There are examples of calling such methods for any class.

i.e:.

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

Or is it better to use

new SampleClass().someMethod();

Please explain in detail.

-1
source share
4 answers

Both are good, but better first ...

If you use

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

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

If you use

new SampleClass().someMethod();

You need another object to call another method of this class.


Another example:

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

this will create objects of the same class how many times your loop will be executed. But if you go with the first option

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

This will not lead to the creation of many objects to call the method.


But yes, if you need to call only one method, and not in a loop, you can go with new SampleClass().someMethod();

+3

, sc , , .

( Java, static), ,

SampleClass.someMethod();
+2

. SampleClass , (sc) .

new SampleClass().method();

.

+1

. , .

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

:

sc.someOtherMethod();
0

Source: https://habr.com/ru/post/1670745/


All Articles