user2714543 user2714543 - 1 month ago 9
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,

-John

Answer Source

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

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

We are saying that do this first:

(MainActivity)this.getActivity()

Then on the result of the above, do this:

.getFoo();

If we don't have the parentheses,

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

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

this.getActivity().getFoo()

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.