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

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

问题描述

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

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

有什么原因比下面的例子更喜欢? p>

示例1



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



Example 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.

像Michael说的,的味道,以及 - 你可能想把代码保存在一个地方。虽然如果你有很多构造函数,你的代码不在一个地方在任何情况下,所以我喜欢初始化。

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天全站免登陆