以下类型的实例化之间有什么区别吗?
我是直接在定义变量的位置设置值,还是在类构造函数中设置值.
如果没有,最佳做法是什么?
“在班上”:
class A {
boolean b = true;
public A(){
}
}
“在构造函数中”:
class B {
boolean b;
public B(){
b = true;
}
}
变量类型仅用于示例.
我看到的唯一区别是,当属性是复杂类型(类)时,构造函数依赖于赋予包含类的构造函数的值:
class A {
B b;
public A(String s){
b = new B(s);
}
}
解决方法:
实际上它们都是等价的.但是,从可读性的角度来看,第一个更具可读性.此外,当有人从IDE导航到变量声明时(例如在Eclipse中按住Ctrl键单击鼠标),很容易看到默认值.
This works well when the initialization value is available and the
initialization can be put on one line. However, this form of
initialization has limitations because of its simplicity. If
initialization requires some logic (for example, error handling or a
for loop to fill a complex array), simple assignment is inadequate.
Instance variables can be initialized in constructors, where error
handling or other logic can be used. To provide the same capability
for class variables, the Java programming language includes static
initialization blocks.
因此,当过程很简单时,您可以轻松使用简单的单线初始化技术.对于复杂的初始化选择,构造函数是可行的方法.
标签:java
来源: https://codeday.me/bug/20190728/1566091.html