MustInitializeFieldInConstructor
If a class has a field, that field must be assigned a value in the constructor of that class.
Constructors must assign values to all fields
Constructors do not need to assign values to all fields
CorrectionHere is what's right.
Fields (if they are not final
) do not need to be initialized explicitly at all.
Moreover, a field may also be initialized where it is declared.
Students may incorrectly believe that the constructor below
must include an assignment to field f
:
class C {
int f;
C() {
f = 9;
}
}
However, this is fine:
class C {
int f;
}
And this is fine as well:
class C {
int f = 19;
}
Note, though, that final
fields must be initialized,
although not necessarily in the constructor
(initializing them where they are declared is fine).
OriginWhere could this misconception come from?
This misconception might stem from knowledge that Java local variables must be initialized before use.
ValueHow can you build on this misconception?
This misconception provides an opportunity to discuss different questions regarding programming styles:
- Should one always explicitly initialize fields (even to the default values of their types)?
- Should fields always be initialized in the constructor (or should they be initialized where they are declared, where possible)?
For advanced students, the misconception also provides an opportunity to introduce the concept of an instance initializer, which is relevant mostly in the context of anonymous classes, where due to the absence of a class name, one cannot write a constructor.
Language
Concepts
Expressible In
Related Misconceptions
Literature References
Qualitative (interviews)
10 undergraduate students
Qualitative study (observations and field notes, audio and video recordings, and collection of artifacts)
47 grade 10 students