Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting reference variable without the double parentheses

Tags:

java

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 ?

like image 323
HPH Avatar asked Jun 08 '26 11:06

HPH


1 Answers

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.

part of precedence table

like image 110
Andreas Avatar answered Jun 11 '26 03:06

Andreas