user2714543 user2714543 - 7 months ago 27
Android Question

Class casting and parentheses

I have seen the following code suggested a number of times for allowing a fragment to access a variable in its activity.

foo = ((MainActivity)this.getActivity()).getFoo();

Now, if it looked like:

foo = (MainActivity)this.getActivity().getFoo();

if would make sense that it was being cast as (MainActivity), however, what does enclosing the entire left side in parentheses do exactly?

Thanks much,


Answer Source

Just like in maths, adding parentheses means "do this first". In the expression:


We are saying that do this first:


Then on the result of the above, do this:


If we don't have the parentheses,


We are saying that do this first, since casting has a low precedence:


then cast the result of the above to MainActivity.

Obviously, the latter expression does not work because there is no getFoo defined in Activity, which is what the getActivity returns.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download