difference between class level instantiation vs method instantiation

后端 未结 6 1562
慢半拍i
慢半拍i 2020-12-21 02:44

what is difference between following variable usages

public class A{

    B b= new B();

    public void doSomething()
    {
        b.callme();
    }
}
         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-21 03:15

    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;
    }
    

提交回复
热议问题