Reputation: 161
i don't know if its asked before (i searched but couldn't find)
Is there any difference between the following 2 code blocks?
1:
// Let's say we want to get variable from non-static object
Object a = new Object();
int varWeWant = a.getVariable();
2:
int varWeWant = new Object().getVariable();
as you see second option is one-line code and i know the java, both codes create object first and retrieve variable via method but i'm not java expert so i wonder if they have any differences ?
Sorry if it is silly question :D i was just wondered this for too long
thanx
Upvotes: 1
Views: 246
Reputation: 7290
The result in varWeWant
is the same.
Some minor differences:
a
variable (that's obvious).a
comsumes a small amount of memory.a
refers to this Object, the garbage collector cannot reclaim its memory. (But compiler and runtime optimizations might be able to free the memory earlier, as soon as a
is no longer used).Upvotes: 0
Reputation: 77
int x = new Object().getVariable(); This is done when the object have one time use. Object a = new Object(); //Creates an object named a This is done when object has multiple variables and functions. This way object is created only once and the variables and functions are called. If we were to use new Object().getSomeFunction() every time then new object is created every time. Its expensive memory wise and more lines has to be written.
Upvotes: 0
Reputation: 45750
The first creates an object that can be referred to later, then calls a method on it.
The second creates a temporary object that can only be used to call that single method.
Really, if you're using the second way, you should question if the object was necessary in the first place. It might make more sense to just make that method a standalone function unless you're using the Builder or similar pattern.
Upvotes: 5
Reputation: 48278
both produce the same BUT option 2 is the object instance an anonymous reference... that means you can not do anything with that object after that statement...
Upvotes: 0