加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 04:13:01 所属栏目:Java 来源:网络整理
导读:以下类型的实例化之间有什么区别吗? 我是直接在定义变量的位置设置值,还是在类构造函数中设置值. 如果没有,最佳做法是什么? “在班上”: class A { boolean b = true; public A(){ }} “在构造函数中”: class B { boolean b; public B(){ b = true; }}
以下类型的实例化之间有什么区别吗?
我是直接在定义变量的位置设置值,还是在类构造函数中设置值.

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

“在班上”:

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键单击鼠标),很容易看到默认值.

查看the official tutorial的内容 –

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.

因此,当过程很简单时,您可以轻松使用简单的单线初始化技术.对于复杂的初始化选择,构造函数是可行的方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读