我应该实例化声明或构造函数中的实例变量吗? [英] Should I instantiate instance variables on declaration or in the constructor?

查看:154
本文介绍了我应该实例化声明或构造函数中的实例变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种方法都有什么优点吗?

Is there any advantage for either approach?

示例1:

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

示例2:

class A {
    B b;

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


推荐答案

b $ b

  • 没有区别 - 实例变量初始化实际上是由编译器放入构造函数中。

  • 第一个变量更易读。

  • 您不能对第一个变体进行异常处理。

  • 另外还有初始化块, ):

    • There is no difference - the instance variable initialization is actually put in the constructor(s) by the compiler.
    • The first variant is more readable.
    • You can't have exception handling with the first variant.
    • There is additionally the initialization block, which is as well put in the constructor(s) by the compiler:

      {
          a = new A();
      }
      


    • 检查 Sun的解释和建议

      本教程


      但是,字段声明不是任何方法的一部分,因此它们不能作为语句执行。相反,Java编译器自动生成实例字段初始化代码,并将其放入该类的构造函数或构造函数中。初始化代码按照它在源代码中出现的顺序插入到构造函数中,这意味着字段初始值设定器可以使用在它之前声明的字段的初始值。

      Field declarations, however, are not part of any method, so they cannot be executed as statements are. Instead, the Java compiler generates instance-field initialization code automatically and puts it in the constructor or constructors for the class. The initialization code is inserted into a constructor in the order it appears in the source code, which means that a field initializer can use the initial values of fields declared before it.

      此外,您可能希望延后初始化您的字段。如果初始化字段是一个昂贵的操作,您可以在需要时立即初始化它:

      Additionally, you might want to lazily initialize your field. In cases when initializing a field is an expensive operation, you may initialize it as soon as it is needed:

      ExpensiveObject o;
      
      public ExpensiveObject getExpensiveObject() {
          if (o == null) {
              o = new ExpensiveObject();
          }
          return o;
      }
      

      最后(如Bill所指出的),为了依赖管理,最好在类中任何地方避免使用 new 运算符。相反,使用依赖注入是更好的 - 即让别人(另一个类/框架)实例化和在类中注入依赖项。

      And ultimately (as pointed out by Bill), for the sake of dependency management, it is better to avoid using the new operator anywhere within your class. Instead, using Dependency Injection is preferable - i.e. letting someone else (another class/framework) instantiate and inject the dependencies in your class.

      这篇关于我应该实例化声明或构造函数中的实例变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆