在构造函数或类中分配属性值,哪个更好? [英] assigning attribute values in constructor or class, which is better?

查看:44
本文介绍了在构造函数或类中分配属性值,哪个更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下实例化类型之间是否有区别?我是直接在定义变量的地方还是在类构造函数中设置值.

Is there any difference between the following types of instantiation? Whether I set the value directly where the variable is defined, or in the class constructor.

如果没有,什么是最佳实践?

If not, what is best practice?

在课堂上":

class A {
    boolean b = true;

    public A(){
    }
}

在构造函数中":

class B {
    boolean b;

    public B(){
        b = true;
    }
}

变量类型仅用于示例.我看到的唯一区别是,当属性是复杂类型(一个类)时,其构造函数取决于为包含类的构造函数提供的值:

The variable type is just for the example. The only difference I see is, when the attribute is a complex type (a class) which constructor depends on values that are given to the constructor of the containing class:

class A {
    B b;
    public A(String s){
        b = new B(s);
    }
}

推荐答案

实际上,它们都是等效的.但是,从可读性的角度来看,第一个更具可读性.另外,当有人从IDE导航到变量声明时,很容易看到默认值(例如 ctrl +在Eclipse中单击鼠标键).

Actually they both are equivalent. From a readability point of view, however, the first one is more readable. Also, it's easy to see the default value when someone navigates to the variable declaration from an IDE (like ctrl + mouse-click in Eclipse).

查看官方教程怎么说-

当初始化值可用并且初始化可以放在一行上.但是,这种形式的初始化由于其简单性而受到限制.如果初始化需要一些逻辑(例如,错误处理或for循环以填充复杂的数组),简单的分配是不够的.实例变量可以在构造函数中初始化,其中错误可以使用其他处理或其他逻辑.提供相同的功能对于类变量,Java编程语言包括static初始化块.

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.

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

So you can easily use the simple one-liner initialization technique when the process is simple. For complex initialization choices, constructors are the way to go.

这篇关于在构造函数或类中分配属性值,哪个更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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