what is difference between following variable usages
public class A{
B b= new B();
public void doSomething()
{
b.callme();
}
}
Case 2:
Is helpful for lazy initialization
In case 1
the object of B
is created when you create object of A
. But if creating B
is heavy operation then you can lazily create it when you actually need B instance.
Lazy Initialization
is helpful when the creating the object is a heavy task and you want to lazily create the object instance only when it is actually being used. But do take care of thread safety
if your class is being shared between threads.
UPDATE: But in your case you are reassigning the reference b everytime the method is called. Which is not Lazy initialization per se.
//example of lazy initialization
public B getB()
{
if (something = = null)
b = new B();
return b;
}