默认构造函数与内联字段初始化 [英] Default constructor vs. inline field initialization

查看:40
本文介绍了默认构造函数与内联字段初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认构造函数和直接初始化对象的字段有什么区别?

What's the difference between a default constructor and just initializing an object's fields directly?

有什么理由更喜欢以下示例之一?

What reasons are there to prefer one of the following examples over the other?

public class Foo
{
    private int x = 5;
    private String[] y = new String[10];
}

示例 2

public class Foo
{
    private int x;
    private String[] y;

    public Foo()
    {
        x = 5;
        y = new String[10];
    }
}

推荐答案

初始化程序在构造函数体之前执行.(如果您同时拥有初始化程序和构造函数,那么构造函数代码会第二次执行并覆盖初始化值)

Initialisers are executed before constructor bodies. (Which has implications if you have both initialisers and constructors, the constructor code executes second and overrides an initialised value)

当您总是需要相同的初始值(例如在您的示例中,给定大小的数组或特定值的整数)时,初始化程序很好,但它可以对您有利也可以对您不利:

Initialisers are good when you always need the same initial value (like in your example, an array of given size, or integer of specific value), but it can work in your favour or against you:

如果您有许多构造函数以不同的方式初始化变量(即具有不同的值),那么初始化程序将毫无用处,因为这些更改将被覆盖且浪费.

If you have many constructors that initialise variables differently (i.e. with different values), then initialisers are useless because the changes will be overridden, and wasteful.

另一方面,如果您有许多使用相同值初始化的构造函数,那么您可以通过将初始化保留在一个地方来节省代码行(并使您的代码更易于维护).

On the other hand, if you have many constructors that initialise with the same value then you can save lines of code (and make your code slightly more maintainable) by keeping initialisation in one place.

就像迈克尔所说的,这也涉及到品味问题 - 您可能希望将代码保存在一个地方.虽然如果你有很多构造函数,你的代码在任何情况下都不会放在一个地方,所以我更喜欢初始化器.

Like Michael said, there's a matter of taste involved as well - you might like to keep code in one place. Although if you have many constructors your code isn't in one place in any case, so I would favour initialisers.

这篇关于默认构造函数与内联字段初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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