Java 我应该在构造函数内还是在构造函数外初始化变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3918578/
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-08-14 06:52:06  来源:igfitidea点击:

Should I initialize variable within constructor or outside constructor

java

提问by Cheok Yan Cheng

When I use Java based on my C++ knowledge, I love to initialize variable using the following way.

当我基于我的 C++ 知识使用 Java 时,我喜欢使用以下方式初始化变量。

public class ME {
    private int i;

    public ME() {
         this.i = 100;
    }
}

After some time, I change the habit to

一段时间后,我改变了习惯

public class ME {
    private int i = 100;

    public ME() {
    }
}

I came across others source code, some are using 1st convention, others are using 2nd convention.

我遇到了其他源代码,有些使用第一种约定,有些使用第二种约定。

May I know which convention do you all recommend, and why?

我可以知道你们都推荐哪种公约,为什么?

采纳答案by sleske

I find the second style (declaration + initialization in one go) superior. Reasons:

我发现第二种风格(一次声明+初始化)更胜一筹。原因:

  • It makes it clear at a glance how the variable is initialized. Typically, when reading a program and coming across a variable, you'll first go to its declaration (often automatic in IDEs). With style 2, you see the default value right away. With style 1, you need to look at the constructor as well.
  • If you have more than one constructor, you don't have to repeat the initializations (and you cannot forget them).
  • 变量的初始化方式一目了然。通常,在读取程序并遇到变量时,您首先会转到它的声明(在 IDE 中通常是自动的)。使用样式 2,您会立即看到默认值。对于样式 1,您还需要查看构造函数。
  • 如果您有多个构造函数,则不必重复初始化(并且您不能忘记它们)。

Of course, if the initialization value is different in different constructors (or even calculated in the constructor), you must do it in the constructor.

当然,如果在不同的构造函数中初始化值不同(甚至在构造函数中计算),则必须在构造函数中进行。

回答by Colin Hebert

I tend to use the second one to avoid a complicated constructor(or a useless one), also I don't really consider this as an initialization (even if it is an initialization), but more like giving a default value.

我倾向于使用第二个来避免复杂的构造函数(或无用的构造函数),而且我并不真正将其视为初始化(即使它是初始化),而更像是给出默认值。

For example in your second snippet, you can remove the constructor and have a clearer code.

例如,在您的第二个代码段中,您可以删除构造函数并获得更清晰的代码。

回答by Josmas

The only problem I see with the first method is if you are planning to add more constructors. Then you will be repeating code and maintainability would suffer.

我在第一种方法中看到的唯一问题是您是否计划添加更多构造函数。然后你会重复代码并且可维护性会受到影响。

回答by Bernard

I recommend initializing variables in constructors. That's why they exist: to ensure your objects are constructed (initialized) properly.

我建议在构造函数中初始化变量。这就是它们存在的原因:确保您的对象正确构造(初始化)。

Either way will work, and it's a matter of style, but I prefer constructors for member initialization.

无论哪种方式都可以,这是一个风格问题,但我更喜欢成员初始化的构造函数。

回答by mklfarha

I think both are correct programming wise,

我认为两者都是正确的编程明智的,

But i think your first option is more correct in an object oriented way, because in the constructor is when the object is created, and it is when the variable should initialized.

但我认为您的第一个选项以面向对象的方式更正确,因为在构造函数中是创建对象的时间,并且是初始化变量的时间。

I think it is the "by the book" convention, but it is open for discussion.

我认为这是“按书”约定,但它是开放的讨论。

Wikipedia

维基百科

回答by Emil

If you initialize in the top or in constructor it doesn't make much difference .But in some case initializing in constructor makes sense.

如果在顶部或构造函数中初始化,则没有太大区别。但在某些情况下,在构造函数中初始化是有意义的。

class String
{
    char[] arr/*=char [20]*/; //Here initializing char[] over here will not make sense.
    String()
    {
        this.arr=new char[0];
    }
    String(char[] arr)
    {
        this.arr=arr;
    }
}

So depending on the situation sometime you will have to initialize in the top and sometimes in a constructor.

因此,根据情况,有时您必须在顶部初始化,有时在构造函数中初始化。

FYI other option's for initialization without using a constructor :

仅供参考,不使用构造函数进行初始化的其他选项:

class Foo
{
    int i;
    static int k;

    //instance initializer block
    {
        //run's every time a new object is created
        i=20;
    }

    //static initializer block
    static{
        //run's only one time when the class is loaded
        k=18;
    }    
} 

回答by kasgoku

Both the options can be correct depending on your situation.

根据您的情况,这两个选项都可以是正确的。

A very simple example would be: If you have multiple constructors all of which initialize the variable the same way(int x=2 for each one of them). It makes sense to initialize the variable at declaration to avoid redundancy.

一个非常简单的例子是:如果您有多个构造函数,所有这些构造函数都以相同的方式初始化变量(每个构造函数的 int x=2)。在声明时初始化变量以避免冗余是有意义的。

It also makes sense to consider final variables in such a situation. If you know what value a final variable will have at declaration, it makes sense to initialize it outside the constructors. However, if you want the users of your class to initialize the final variable through a constructor, delay the initialization until the constructor.

在这种情况下考虑最终变量也是有意义的。如果您知道 final 变量在声明时将具有什么值,则在构造函数之外对其进行初始化是有意义的。但是,如果您希望类的用户通过构造函数初始化最终变量,请将初始化延迟到构造函数。

回答by Steve Emmerson

One thing, regardless of how you initialize the field, use of the finalqualifier, if possible, will ensure the visibility of the field's value in a multi-threaded environment.

一件事,无论您如何初始化字段,final如果可能,使用限定符将确保字段值在多线程环境中的可见性。

回答by Ishtar

I would say, it depends on the default. For example

我会说,这取决于默认的. 例如

public Bar
{
  ArrayList<Foo> foos;
}

I would make a new ArrayListoutside of the constructor, if I always assume fooscan not be null. If Baris a valid object, not caring if foosis null or not, I would put it in the constructor.

new ArrayList如果我总是假设foos不能为空,我会在构造函数之外创建一个。如果Bar是一个有效的对象,不关心是否foos为空,我会把它放在构造函数中。

You might disagree and say that it's the constructors job to put the object in a valid state. However, if clearly allthe constructors should do exactly the same thing(initialize foos), why duplicate that code?

您可能不同意并说将对象置于有效状态是构造函数的工作。但是,如果显然所有构造函数都应该做完全相同的事情(初始化foos),为什么要重复该代码?

回答by Joseph Cozad

I have the practice (habit) of almost always initializing in the contructor for two reasons, one in my opinion it adds to readablitiy (cleaner), and two there is more logic control in the constructor than in one line. Even if initially the instance variable doesn't require logic, having it in the constructor gives more flexibility to add logic in the future if needed.

我有几乎总是在构造函数中初始化的实践(习惯)有两个原因,一个在我看来它增加了可读性(更干净),两个在构造函数中比在一行中有更多的逻辑控制。即使最初实例变量不需要逻辑,在构造函数中使用它也可以更灵活地在将来根据需要添加逻辑。

As to the concern mentioned above about multiple constructors, that's easily solved by having one no-arg constructor that initializes all the instance variables that are initilized the same for all constructors and then each constructor calls this() at the first line. That solves your reduncancy issues.

至于上面提到的关于多个构造函数的问题,通过使用一个无参数构造函数来初始化所有构造函数的所有实例变量,然后每个构造函数在第一行调用 this() ,这很容易解决。这解决了您的冗余问题。