Default constructor does not initialize the instance members of the class?

前端 未结 7 2612
清酒与你
清酒与你 2021-02-13 03:05

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 cla

7条回答
  •  生来不讨喜
    2021-02-13 03:32

    No, it is not the default constructor which initialize the instance variables for you. Each type has a default value. The moment you created the object, the default value is used.

    So if you do not explicitly initialize the instance variables, they will be still using the default values defined for them implicitly.

    i.e. 0 for int, null for reference type.. etc

    However, it is worth noting that we should not take it for granted that a default value is given, and choose not to initialize the variables.


    You may try defining an empty constructor which override the default constructor with empty implementation. You will realize all instance variables will still be initialized.

提交回复
热议问题