Calling a method on a new object in Java without parentheses: order of operations violation?

Kyle Strand picture Kyle Strand · May 13, 2013 · Viewed 8.7k times · Source

According to this table of Java operator precedence and associativity, member access has higher precedence than the new operator.

However, given a class myClass and a non-static member function myFunction, the following line of code is valid:

new myClass().myFunction();

If . is evaluated before new, how can this line be executed? In other words, why aren't parentheses required?

(new myClass()).myFunction();

My guess is that since () shares precedence with ., the myClass() is evaluated first, and so the compiler knows even before evaluating the new keyword that the myClass constructor with zero parameters is being called. However, this still seems to imply that the first line should be identical to new (myClass().myFunction());, which is not the case.

Answer

Jack picture Jack · May 13, 2013

This is because of how the grammar of Java language is defined. Precedence of operators comes into play just when the same lexical sequence could be parsed in two different ways but this is not the case.

Why?

Because the allocation is defined in:

Primary: 
  ...
  new Creator

while method call is defined in:

Selector:
  . Identifier [Arguments]
  ...

and both are used here:

Expression3: 
  ...
  Primary { Selector } { PostfixOp }

so what happens is that

new myClass().myFunction();

is parsed as

         Expression
             |
             |
    ---------+--------
    |                |
    |                |
  Primary        Selector
    |                |
    |                |
 ---+---            ...
 |     |
new   Creator 

So there is no choice according to priority because the Primary is reduced before. Mind that for the special situation like

new OuterClass.InnerClass()

the class name is actually parsed before the new operator and there are rules to handle that case indeed. Check the grammar if you like to see them.