Should I instantiate instance variables on declaration or in the constructor?

前端 未结 15 1883

Is there any advantage for either approach?

Example 1:

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

Example 2:

class A {
    B b;         


        
15条回答
  •  -上瘾入骨i
    2020-11-22 06:56

    Example 2 is less flexible. If you add another constructor, you need to remember to instantiate the field in that constructor as well. Just instantiate the field directly, or introduce lazy loading somewhere in a getter.

    If instantiation requires more than just a simple new, use an initializer block. This will be run regardless of the constructor used. E.g.

    public class A {
        private Properties properties;
    
        {
            try {
                properties = new Properties();
                properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("file.properties"));
            } catch (IOException e) {
                throw new ConfigurationException("Failed to load properties file.", e); // It's a subclass of RuntimeException.
            }
        }
    
        // ...
    
    }
    

提交回复
热议问题