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


according this table of java operator precedence , associativity, member access has higher precedence new operator.

however, given class myclass , non-static member function myfunction, following line of code valid:

new myclass().myfunction();

if . evaluated before new, how can line executed? in other words, why aren't parentheses required?

(new myclass()).myfunction();

my guess since () shares precedence ., myclass() evaluated first, , compiler knows before evaluating new keyword myclass constructor 0 parameters being called. however, still seems imply first line should identical new (myclass().myfunction());, not case.

this because of how grammar of java language defined. precedence of operators comes play when same lexical sequence parsed in 2 different ways not case.

why?

because allocation defined in:

primary:    ...   new creator 

while method call defined in:

selector:   . identifier [arguments]   ... 

and both used here:

expression3:    ...   primary { selector } { postfixop } 

so happens that

new myclass().myfunction(); 

is parsed as

         expression              |              |     ---------+--------     |                |     |                |   primary        selector     |                |     |                |  ---+---            ...  |     | new   creator  

so there no choice according priority because primary reduced before. mind special situation like

new outerclass.innerclass() 

the class name parsed before new operator , there rules handle case indeed. check grammar if see them.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -