java 类中的属性值_java – 在构造函数或类中分配属性值,哪个更好?

以下类型的实例化之间有什么区别吗?

我是直接在定义变量的位置设置值,还是在类构造函数中设置值.

如果没有,最佳做法是什么?

“在班上”:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值