I’m very new to developing on Android and the Java language in general and I can’t seem to find an explanation on why the following statement has “(TabHost)” after the “=”:
TabHost tabHost=(TabHost)findViewById(R.id.tabHost);
as opposed to:
TabHost tabHost = getTabHost();
They do the same thing, right? Why use either of them? Also, please explain the syntax of the first code specifically, please.
Thank you.
The first case returns a generic
View, which is the superclass from which all other views inherit. You have to cast it to aTabHostsince Java doesn’t know it’s supposed to be one. It translates to saying “get me the View with this id, which, by the way, is supposed to be a TabHost”.The second instance is a method that is part of the
TabActivityclass which specifically returns aTabHostobject, so there’s no need for casting.