Given the below two classes :
class A {}
class B extends A {
int b;
}
Based on the following operators precedence table : http://www.cs.bilkent.edu.tr/~guvenir/courses/CS101/op_precedence.html.
Both operators () and . have the same priority and they evaluated from left to right (associativity).
A a = new B();
assert (B)a.b == 0;
the above code snippet should compile and asserts successfully as the parentheses operator is evaluated first (casting reference a to type B) then accessing the casted reference's b member variable which returns a value of 0.
Why is the above statement isn't the case ?
You are confusing the () Parentheses in precedence 15 with the ( type ) Unary type cast in precedence 13.
The . Member selection in precedence 15 is higher than the type cast, so (B)a.b means (B) (a.b), which is why you need to write ((B) a).b to get what you want.

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With