我应该在构造函数或外部构造函数中初始化变量 [英] Should I initialize variable within constructor or outside constructor

查看:165
本文介绍了我应该在构造函数或外部构造函数中初始化变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

public class ME {
    private int i;

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

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

After sometime, I change the habit to

public class ME {
    private int i = 100;

    public ME() {
    }
}

我遇到了其他的源代码,有些人正在使用第1次约定,有些人正在使用第2次约定。

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?

推荐答案

我发现第二种风格(声明+初始化一次性)优越。理由:

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


  • 它使变量初始化变得清晰。通常,在阅读程序并遇到变量时,您将首先转到其声明(通常在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.

这篇关于我应该在构造函数或外部构造函数中初始化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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