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

大兔子大兔子 提交于 2019-11-28 18:39:21

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.

I disagree with the conclusion drawn from Jack's diagram. When a grammar is written its nonterminals and structure are designed to implement the precedence and associativity of the language being described. That's why the classic BNF for expressions introduces the "term" and "factor" nonterminals - to enforce the normal multiplication before addition precedence of arithmetic.

So the fact that "Primary -> new Creator" and "Expression -> Primary Selector" in the grammar means that "new Creator" is at a higher precedence level than "Primary Selector".

It seems to me that the grammar is evidence that the Java operator precedence and associativity table is incorrect.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!