java - 在现场实例化和在构造函数中实例化有什么区别?

标签 java

这样做有什么区别:

public class SomeClass {
    SomeObject obj = new SomeObject();
    //rest of the code
}

还有这个

public class SomeClass {
    SomeObject obj;
    public SomeClass(){
       obj = new SomeObject();
    }
    //rest of the code
}

最佳答案

根据章节12.5 Creation of New Class Instances Java 语言规范:

Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure:

  1. Assign the arguments for the constructor to newly created parameter variables for this constructor invocation.
  2. If this constructor begins with an explicit constructor invocation of another constructor in the same class (using this), then evaluate the arguments and process that constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason; otherwise, continue with step 5.
  3. This constructor does not begin with an explicit constructor invocation of another constructor in the same class (using this). If this constructor is for a class other than Object, then this constructor will begin with an explicit or implicit invocation of a superclass constructor (using super). Evaluate the arguments and process that superclass constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, continue with step
  4. Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5. (In some early implementations, the compiler incorrectly omitted the code to initialize a field if the field initializer expression was a constant expression whose value was equal to the default initialization value for its type.)
  5. Execute the rest of the body of this constructor. If that execution completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, this procedure completes normally.

所以区别只是步骤(第 4 步或第 5 步),但结果是相同的。

关于java - 在现场实例化和在构造函数中实例化有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1585271/

相关文章:

java - 将循环重构为android中的流

java - 我的动画按钮显示的时间不够长

java - Selenium 2 和 OperaDriver : java.net.BindException

java - 从 JPA 注释生成 DDL

java - 合并来自不同声明的多个@TestExecutionListeners?

轻松设计UI的Java Web框架

java - 过滤器中的自定义 propertyConverter 在 Neo4j OGM 中被覆盖

java - 对于 Java 中的静态帮助器类,使用泛型还是对象类型更好?

java - 服务层的 Spring AOP

java - 时区转换和日期显示不正确