difference between class level instantiation vs method instantiation

后端 未结 6 1552
慢半拍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:05

    The REAL difference here is that do you want a different instance of B each time doSomething is called? In the second case this is true but it also means that your class is not thread-safe if there are any other methods using B. And if there are NOT any other methods in the class using B why not make it a method-scoped variable?

提交回复
热议问题