A constructor needs to return an object, and it needs a return type corresponding to its class.
Constructors need to return objects
Constructors cannot return anything
CorrectionHere is what's right.
A constructor does not return any value.
It does not create anything,
it just initializes the given object (the object pointed to by
OriginWhere could this misconception come from?
This misconception may come from how constructors are used:
Object o = new Object();
In the above code, the expression
new Object() produces a value.
Students may believe that for it to produce a value,
the constructor has to produce that value.
They may believe that this expression is only a constructor call.
However, the object is not produced by the constructor,
but by the
new Object() expression,
which allocates the object, calls the constructor to initialize it,
and then produces the initialized object.
SymptomsHow do you know your students might have this misconception?
Do your students write:
- Constructors that
- Constructors (of a class C) that
return new C()
- Constructors with a return type in their header