It’s impossible to write an object allocation expression (e.g.,
on the left-hand side of a method invocation (e.g.,
or field access (e.g.,
Method calls or field accesses cannot be chained to a constructor invocation
Method calls or field accesses can be chained to a constructor invocation
CorrectionHere 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();
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.
new C() evaluates to an object reference of type
and it is perfectly legal to invoke a method on that object reference.
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
OriginWhere 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();
ValueHow 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,