在构造函数中的初始化和初始化 [英] Initialization in definition vs. initialization in constructor

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

问题描述

在Java中,但是在其他OO语言中,在其定义中初始化属性之间有区别,如

In Java, but in other OO languages as well, is there a difference between initializing an attribute in its definition, as in

class Example {
    public Sample sample_attribute = new Sample();
}

并使用构造函数初始化?

and using a constructor to initialize it?

class Example {
    public Sample sample_attribute;

    public Example() {
        sample_attribute = new Sample();
    }
}



我不能想到任何实际差异,一?否则,是否有一种方法比另一种方法更好,即使它们有相同的结果?

I could not think of any practical difference, is there one? Otherwise, are there cases in which one method is better than the other, even if they have the same result?

推荐答案


  1. 将字段设置为默认初始值(0,false,null)


  2. 调用超类的构造函数

  3. 调用对象的构造函数(但不要执行
    的构造函数) li>使用初始化程序和初始化块初始化字段
  4. 执行构造函数的主体

  1. Set fields to default initial values (0, false, null)
  2. Call the constructor for the object (but don't execute the body of the constructor yet)
  3. Invoke the constructor of the superclass
  4. Initialize fields using initializers and initialization blocks
  5. Execute the body of the constructor

,第一种情况将在第四步中初始化变量 sample_attribute ,第二步将在第五步中初始化变量 sample_attribute

So, first case will be initialize the variable sample_attribute in 4th step, second will initialize the variable sample_attribute in 5th step. It's all depends on your requirement.

如果你想访问Constructor中的任何变量,你需要使用第一种情况。

If you want to access any of the variables from Constructor, you need to use 1st case.

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

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