MustInitializeFieldInConstructor

Misconception:

If a class has a field, that field must be assigned a value in the constructor of that class.

Incorrect

Constructors must assign values to all fields

Correct

Constructors do not need to assign values to all fields

Correction
Here 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).

Origin
Where could this misconception come from?

This misconception might stem from knowledge that Java local variables must be initialized before use.

Value
How 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.

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.