Assuming that there is a class ClassA which gives a value that I need through non-static method.
In case when I just need a value from an instance of the ClassA, I guess there are two possible choices.
double value =0 ; // The value I actually need, the object is just transitory
1) ClassA a = new ClassA (hogehoge);
value = a.getValue();
2) value = new ClassA(hogehoge).getValue();
I know there maybe an advantage or disadvantage for both. but generally speaking what is the difference between them?
in case 2), memory use is smaller than 1) or....
If the class has an initializer method, this method is used to get the attributes (i.e. the state) of the new object properly set up. A special method in Python (called __init__) that is invoked automatically to set a newly created object's attributes to their initial (factory-default) state.
The constructor method is used to initialize data. It is run as soon as an object of a class is instantiated. Also known as the __init__ method, it will be the first definition of a class and looks like this: class Shark: def __init__(self): print("This is the constructor method.")
Calling an object's method is similar to getting an object's variable. To call an object's method, simply append the method name to an object reference with an intervening '. ' (period), and provide any arguments to the method within enclosing parentheses.
A constructor is used to initialize an object when it is created.
Actually this two piece of code will have a small difference:
***** Class1.p
8: invokespecial #4 // Method ClassA."<init>":(Ljava/lang/String;)V
11: astore_3
12: aload_3
13: invokevirtual #5 // Method ClassA.getValue:()D
16: dstore_1
17: dload_1
18: dreturn
}
***** CLASS2.P
8: invokespecial #4 // Method ClassA."<init>":(Ljava/lang/String;)V
11: invokevirtual #5 // Method ClassA.getValue:()D
14: dstore_1
15: dload_1
16: dreturn
}
*****
I.e. we see here two additional instructions for variant #1:
11: astore_3
12: aload_3
But it seems, that after jvm warms-up these instructions will be optimized (eliminated) and it will be no difference at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With