ConstructorAllocates

Misconception:

A constructor must allocate the new object, i.e., it must use new.

Incorrect

The constructor allocates the object

Correct

The constructor does not allocate the object, it just initializes it

Correction
Here is what's right.

The constructor does not allocate an object; it only initializes the object. The object is created by Java right before the constructor is invoked. The new is responsible for creating (allocating) the object. The constructor is only responsible for properly setting up the object’s initial state (which ultimately involves assigning values to the object’s instance variable).

Note that this interpretation is consistent with the fact that a constructor does not return the object it initialized.

Symptoms
How do you know your students might have this misconception?

Here is an example occurrence of this misconception, when students had to create a “wrapper” class for ints:

class IntHolder {

  private int holder;

  public IntHolder(int holder) {
    holder = new IntHolder();
  }

}

Value
How can you build on this misconception?

This misconception is a great opportunity to discuss allocation versus initialization. In Java, an object is allocated before its constructor is called. The constructor then initializes the object, i.e., it sets the values of all the fields of that object.

Opportunity to Look Under the Hood

If you are familiar with Java bytecode, and your students are ready for this, you could use javap to disassemble a Java class to show how new C() is compiled into two separate bytecode instructions:

new C                       // allocate an instance of class C
...
invokespecial C.<init>()    // call constructor C()

Opportunity to Discover Related Issues

If students use new C() inside a constructor C(), you may discuss how this would recursively invoke the constructor. Have them try this out, and see how it leads to an infinite recursion (i.e., a stack overflow).

If students assign the result of the instantiation to an instance variable, have them check for type compatibility. If the class essentially is a “wrapper” class (like in the TimeStamp and Holder examples above), the instance variable will be of a primitive type, but the class will be of a class type. Discuss the difference.

If students assign the result of the instantiation to this, then they also have the ThisAssignable misconception.

If students return the result of the instantiaion, then they also have the ConstructorReturnsObject misconception.

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.