operator precedance: new MyClass.method()

R

Robert

Hi,
According to the operator precedence table, the dot operator has a higher
precedence than the 'new' operator:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/expressions.html

Therefore when I write
new myClass.method()
it should, according to this table, be parsed as
new (myClass.method())
which is nonsensical and doesn't compile.
It seems to be parsed as this instead:
(new myClass).method()
Is there an explanation?

****
sample code:
****
public class C {
public int i = 0;

public C(int i) {
this.i = i;
}

public int getI() {
return i;
}

public static void main(String args[]){
System.out.println(new C(20).getI());
// is parsed as:
//System.out.println( (new C(20)).getI() ); ==> ok
// but according to precedance table should be parsed as:
//System.out.println( new (C(20).getI()) ); ==> wrong
}
}
 
J

John C. Bollinger

Robert said:
Hi,
According to the operator precedence table, the dot operator has a higher
precedence than the 'new' operator:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/expressions.html

Therefore when I write
new myClass.method()
it should, according to this table, be parsed as
new (myClass.method())
which is nonsensical and doesn't compile.
It seems to be parsed as this instead:
(new myClass).method()
Is there an explanation?

Sure there's an explanation. The operator precedence table you cite is
wrong.

The Java Language Specification does not contain an explicit operator
precedence table, and Sun has produced comments to the effect that it
doesn't need one because the precedence is implicit in the formal
grammar (which is not completely true). From the grammar in the 2nd
edition of the JLS (which is flawed, BTW) the new operator has the same
precedence as the . operator in at least some circumstances, and a
higher precedence in all others.

All of that is moot, though. The JLS, Java tutorial, and many other
sources all recommend that you use parentheses to make the required
order of evaluation clear to both humans and compilers.


John Bollinger
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top