默认构造函数不初始化类的实例成员? [英] Default constructor does not initialize the instance members of the class?

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

问题描述

我遇到了一个询问
的问题关于默认构造函数,以下哪一项是正确的?

I encountered a question that asks "Which of the following are true about the "default" constructor?"

和一个选项
它初始化了类的实例成员。
是不正确的选择。

and an option "It initializes the instance members of the class." was incorrect choice.

现在我的理解是,如果我们有一个代码,例如

Now my understanding was that if we have a code such as

    Class Test {
        String name;
    }

然后编译器创建看起来像

then the compiler creates default constructor that looks like

    Class Test {
        String name;
        Test(){
            super();
            name = null;
        }
    }

不是初始化实例成员名称的默认构造函数= null?

Isn't the default constructor initializing the instance member name=null ?

推荐答案

类构造函数不是初始化的,JVM就是这样做的。创建对象的内存后,对象的成员将默认初始化为某个可预测的值,该值将成为其默认值。

The class constructor is not the one doing the initialization, the JVM does this. After memory for the object is created, the members of the object are default initialized to some predictable value, which becomes their default value.

根据规范



  • 每个类变量,实例变量或数组组件在创建时都使用默认值进行初始化(§15.9§15.10.2):


    • 对于type byte,默认值为零,即(byte)0 的值。

    • 对于类型short,默认值为零,即的值(短)0

    • 对于int类型,默认值为零,即 0

    • 对于long类型,默认值为零,即 0L

    • 对于float类型,默认值为正零,即 0.0f

    • 对于double类型,默认值为正零,即 0.0d

    • 对于char类型,默认值为空字符,即'\ u0000'

    • 对于类型布尔值,默认值为 false

    • 适用于所有参考类型(§ 4.3)),默认值为 null

  • Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):
    • For type byte, the default value is zero, that is, the value of (byte)0.
    • For type short, the default value is zero, that is, the value of (short)0.
    • For type int, the default value is zero, that is, 0.
    • For type long, the default value is zero, that is, 0L.
    • For type float, the default value is positive zero, that is, 0.0f.
    • For type double, the default value is positive zero, that is, 0.0d.
    • For type char, the default value is the null character, that is, '\u0000'.
    • For type boolean, the default value is false.
    • For all reference types (§4.3), the default value is null.

您的假设很接近,但事实是,在构造函数参数被评估之前 - 甚至可以为每个字段分配值 - 那些字段已经保持默认值,这是由JVM完成的。

Your assumption is close but the fact is, before the constructor parameters are even evaluated - before it can even assign a value to each of the fields - those fields already hold their default values, and this is done by the JVM.

阅读小节§15.9.4了解如何执行初始化过程

Read subsection §15.9.4 to understand how the initialization process is carried out

这篇关于默认构造函数不初始化类的实例成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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