difference between class level instantiation vs method instantiation

后端 未结 6 1567
慢半拍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条回答
  •  萌比男神i
    2020-12-21 02:58

    The first case is called inline initialization. It will happen before the body of any constructors run but after the call to the super constructor.

    In the second case b is not initialized until doSomething is called().

    As for which is better, that depends on your program logic. If you want a new instance every time doSomething is called, the second way is better. If you'd prefer to lazy load b then modify it to be

    if (b == null) b = new B(); 
    return b;
    

    Personally I generally allocate instance variables in the constructor for the sake of readability.

    public class A {
      B b;
    
      public A() {
        b = new B();
      } 
    }
    

提交回复
热议问题