java类成员初始化 [英] java class member initialisation

查看:109
本文介绍了java类成员初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个多年的Java程序员,我对此感到有些ham愧,但这是这样的:

在构造过程中分配对象与在声明相关字段时直接分配对象之间有区别吗?也就是说,以下两个之间是否有区别:

I am a bit ashamed to ask that, being a Java programmer for years, but here goes:
Is there a difference between allocating objects during construction, and doing so directly when declaring the relevant field? That is, is there a difference between the following two:

public class MyClass{
    MyObj obj=new MyObj();
}

AND

public class MyClass{
    MyObj obj;
    public MyClass() {
        obj=new MyObj();
    }
}

当然,我认为此特定的init不依赖

Of course, I assume this specific init's do not rely on outside parameters.

推荐答案


实例变量初始化在之前构造函数调用完成

不好做。

您可以限制用户访问const。如果要在初始化之前执行某些操作。

Its not good to do.
You can restrict user from call of const. if you want to perform certain operation before initialization.

最佳做法:



  1. 不要使用声明中的默认值初始化(null,false,0、0.0 ...)。

  2. 首选初始化

  3. 如果由于构造函数参数而导致字段值发生变化,则在构造函数中添加>初始化

  4. 保持一致。 (最重要的规则)

  1. Don't initialize with the default values in declaration (null, false, 0, 0.0...).
  2. Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.
  3. If the value of the field changes because of a constructor parameter put the >initialization in the constructors.
  4. Be consistent in your practice. (the most important rule)


来自此处

这篇关于java类成员初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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