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

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

问题描述

这两种方法有什么优势吗?

Is there any advantage for either approach?

示例 1:

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

示例 2:

class A {
    B b;

    A() {
         b = new 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天全站免登陆