o.f.field are illegal.
Member accesses cannot be chained together
Member accesses can be chained together
CorrectionHere is what's right.
The following two code snippets both invoke a method
and then invoke method
work() on the object returned by method
C o = m(); o.work();
Here we see the corresponding expressions trees (first example on the left, second one on the right):
m() evaluates to an object reference of type
and it is perfectly legal to invoke a method on that object reference.
It’s equally valid to access a field on such an object:
m().f = 19;
19 to the
f field of the object returned by
OriginWhere could this misconception come from?
Students 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:
m().field = 19; m().method();