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

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

问题描述

当我基于我的 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 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?

推荐答案

我觉得第二种风格(声明 + 一次性初始化)更胜一筹.原因:

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