在声明初始化和构造函数初始化之间的区别 [英] Difference between initialization at declaration and initialization in constructor

查看:226
本文介绍了在声明初始化和构造函数初始化之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两者之间的区别是什么,更为优选?

  public class foo {

int i = 2;

}

public class foo {

int i;
foo(){

i = 2;

}
}


解决方案

在你的例子中,行为语义没有区别。在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.

这篇关于在声明初始化和构造函数初始化之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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