且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在声明初始化和构造函数初始化之间的区别

更新时间:2022-12-13 14:14:43

在你的例子中,行为语义没有区别。在Java中,所有实例字段初始化器(和实例块)在超类初始化之后,之前在构造函数的主体之前执行;请参阅 JLS 12.5 。 / p>

区别在于代码可读性和(在其他示例中)避免重复编码和脆弱性 1 。这些需要根据具体情况进行评估。



这也值得注意,有些情况下你必须在构造函数中初始化;即当初始化依赖于构造函数参数时。






1 - 重复性和脆弱性问题是翻转的的同一件事。如果你有多个构造函数,初始化构造函数方法往往导致重复。如果你添加额外的字段,你可能要添加初始化到所有相关的构造函数;即脆弱。


What is the difference between the following two, and which is more preferable??

public class foo {

    int i = 2;

}

public class foo {

  int i;
    foo() {

        i = 2;

    }
}

In your example, there is no difference in behavioural semantics. In Java, all instance field initializers (and instance blocks) are executed after superclass initialization, and before the body of the constructor; see JLS 12.5.

The difference lies in code readability and (in other examples) avoiding repetitious coding and fragility1. These need to be assessed on a case-by-case basis.

It is also worth noting that there are some cases where you have to initialize in the constructor; i.e. when the initialization depends on a constructor parameter.


1 - The repetitiousness and fragility issues are flip-sides of the same thing. If you have multiple constructors, the "initialize in constructor" approach tends to lead to repetition. And if you add extra fields, you might to add the initialization to all relevant constructors; i.e. fragility.