CannotChainMemberToConstructor

Misconception:

It’s impossible to write an object allocation expression (e.g., new C()) on the left-hand side of a method invocation (e.g., new Point().toString()) or field access (e.g., new Point().a).

Incorrect

Method calls or field accesses cannot be chained to a constructor invocation

Correct

Method calls or field accesses can be chained to a constructor invocation

Correction
Here is what's right.

The following two code snippets both allocate a new object and invoke method m on that new object:

C o = new C();
o.m();
new C().m()

Here we see two expressions trees: the left one represents the second line of the first example, the right one the only line of the second example.

The expression new C() evaluates to an object reference of type C, and it is perfectly legal to invoke a method on that object reference. So new C().m() is fine: this allocates an object of class C and invokes method m on that new object.

It’s equally valid to access a field on such an object:

new C().f = 19;

This allocates an object of class C and writes 19 to its f field.

Origin
Where could this misconception come from?

This might stem from ObjectsMustBeNamed.

Alternatively, students may have a misconception about operator precedence. They might agree that ( new C() ).m() works, but might wrongly believe that new C().m() is equivalent to new ( C().m() ).

Students also may believe that there cannot be an expression on the left side of the dot. They may have encountered field accesses and method invocations in only a limited number of forms, such as:

variable.field = 19;
    this.field = 19;
         field = 19;
variable.method();
    this.method();
         method();

They may never have seen a primary expression on the left side of the dot:

 new C().field = 19;
 new C().method();

Value
How can you build on this misconception?

If you see this misconception, investigate! It might help you to identify a deeper misconception around the idea that new C() is not an expression on its own, i.e. ObjectsMustBeNamed.

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.