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

问题描述

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

  public class foo {

int i = 2;

}

public class foo {

int i;
foo(){

i = 2;

}
}


解决方案

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

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



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







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 fragility. 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.


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

08-18 14:02