CannotChainMemberAccesses

Misconception:

Expressions like o.m().method() or o.m().field or o.f.method() or o.f.field are illegal.

Incorrect

Member accesses cannot be chained together

Correct

Member accesses can be chained together

Correction
Here is what's right.

The following two code snippets both invoke a method m() and then invoke method work() on the object returned by method m():

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

Here we see the corresponding expressions trees (first example on the left, second one on the right):

The expression m() evaluates to an object reference of type C, 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;

This writes 19 to the f field of the object returned by m().

Origin
Where 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();

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.