Java defining or initializing attributes of a class

前端 未结 3 1641
生来不讨喜
生来不讨喜 2021-02-05 06:35

Is there a difference between defining class attributes and initializing them? Are there cases where you want to do one over the other?

Exampl

3条回答
  •  你的背包
    2021-02-05 07:05

    Shanku and Morpheus answered the question correctly. First, you will get a compile error setting your primitive int variable "integer" to null; you can only do that for Objects. Second, Shanku is right that Java assigns default values to instance variables, which are "integer" and "random" in your example code; instance variables are viewable within the class or beyond depending on the scope (public, private, protected, package).

    However, default values are not assigned for local variables. For instance, if you assigned a variable in your constructor like "int height;" then it will not be initialized to zero.

    I would recommend reading the Java variable documentation, which describe the variables very well and furthermore you could also look over the Java tutorials, which again are great reading material.

提交回复
热议问题