java 在声明中初始化与在构造函数中初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7003552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:13:37  来源:igfitidea点击:

Initializing on declaration vs initializing in constructors

java

提问by amrhassan

Possible Duplicate:
Should I initialize variable within constructor or outside constructor

可能的重复:
我应该在构造函数内还是在构造函数外初始化变量

I was wondering, which is a better practice and why. Should I initialize class fields upon declaration, or should I do it in the constructor? Given that it's a simple one-line initialization.

我想知道,哪个是更好的做法以及为什么。我应该在声明时初始化类字段,还是应该在构造函数中初始化?鉴于这是一个简单的单行初始化。

class Dude
{
    String name = "El duderino";

    Dude() {
        // irrelevant code
    }
}

vs.

对比

class Dude
{
    String name;

    Dude() {
        name = "El duderino";

        // irrelevant code
    }
}

Edit:I am aware of the situations where one of the styles would be preferred over the other like in the case of executing initializer code that might throw an exception. What I'm talking about here are cases when both styles are absolutely equivalent. Both ways would accomplish the same task. Which should I use then?

编辑:我知道在执行可能引发异常的初始化程序代码的情况下,其中一种样式比另一种样式更受欢迎。我在这里谈论的是两种风格绝对等效的情况。这两种方式都可以完成相同的任务。那我应该用哪个?

采纳答案by erickson

If the member can onlybe set via an accessor (a "setter" method), I prefer the first style. It provides a hint that the initialized value is the default upon construction.

如果只能通过访问器(“setter”方法)设置成员,我更喜欢第一种样式。它提供了一个提示,即初始化值是构造时的默认值。

If the member can be specified during construction, I generally pass the default value to an appropriate constructor from constructor with fewer parameters. For example,

如果可以在构造过程中指定成员,我通常将默认值从具有较少参数的构造函数传递给适当的构造函数。例如,

final class Dude {

  private final String name;

  Dude() {
    this("El Duderino");
  }

  Dude(String name) {
    this.name = name;
  }

}

回答by mtahmed

The first one is used usually to initialize static variable and should be used only for that purpose.

第一个通常用于初始化静态变量,应该仅用于该目的。

In this case, you should use the second method.

在这种情况下,您应该使用第二种方法。

Please correct me if I am wrong.

如果我错了,请纠正我。

回答by CalMlynarczyk

It is best to declare variables inside the constructor for the sake of consistency. A variable may require something like a loop or an if-else statement to initialize it, which can not be done in the declaration without placing the operation inside of a method.

为了一致性,最好在构造函数中声明变量。变量可能需要诸如循环或 if-else 语句之类的东西来初始化它,如果不将操作放在方法内部,则无法在声明中完成。

The exception to this rule is static variables, which should be declared outside of the constructor.

这条规则的例外是静态变量,它应该在构造函数之外声明。

回答by Vineet Reynolds

Single-line declarations cannot contain complex initialization logic.

单行声明不能包含复杂的初始化逻辑。

If you initialize a variable as:

如果将变量初始化为:

class AnotherClass
{
    MyClass anObject = new MyClass(); //MyClass() throws a checked exception.
}

then you'll find that you cannot provide the initial value in the single line. You'll need to place such code in a block, that quite obviously goes inside a constructor (or in a non-static initialization block):

那么你会发现你不能在单行中提供初始值。您需要将这样的代码放在一个块中,这很明显是在构造函数中(或在非静态初始化块中):

Using a constructor:

使用构造函数:

class AnotherClass
{
    MyClass anObject;

    AnotherClass()
    {
        try{this.anObject = new MyClass();}catch(SomeException e){/*handle exception.*/}
    }
}

Using a initialization block:

使用初始化块:

class AnotherClass
{
    MyClass anObject;

    {
        try{this.anObject = new MyClass();}catch(SomeException e){/*handle exception.*/}
    }
}

I find that the latter makes for less understandable code, as the declaration and initialization are separated from each other, and the initialization does not occur in a constructor coded by the developer (although there is no difference at runtime).

我发现后者使代码更难理解,因为声明和初始化彼此分开,并且初始化不会发生在开发人员编写的构造函数中(尽管在运行时没有区别)。

The same goes for other complex routines involved in initialization of fields. For example, if you intend to initialize an Arrayor a Collectionand set the contents of the array/collection to some default value, then you should do so inside a constructor:

这同样适用于涉及字段初始化的其他复杂例程。例如,如果您打算初始化 anArray或 aCollection并将数组/集合的内容设置为某个默认值,那么您应该在构造函数中执行此操作:

class AnotherClass
{
    Integer[] integers;

    AnotherClass()
    {
        this.integers = new Integer[10];
        for(Integer integer: integers)
        {
            integer = Integer.MIN_VALUE;
        }
    }
}