I am writing an Android app and just was curious about why we must always type-cast in Android. I understand that we need to be sure of the type so that our code runs proper
DrawerLayout
is a subclass of View
. A DrawerLayout
object automatically has all the methods that a View
has, but defines some methods of its own that are specific to DrawerLayout
s. If you don't cast it, you can't use any of those DrawerLayout
methods; you can only use the methods defined for all View
s.
The type-casting doesn't do anything, really. findViewById
is declared to return a View
, since it can return all different kinds of View
s. But in reality, it will often return an object of some other class, that is a subclass of View
. The type-cast just checks to make sure that the returned object is really an instance of DrawerLayout
(or one of its subclasses); if not, an exception is thrown, but if it is, you can now look at the object as a DrawerLayout
and use the DrawerLayout
methods.
findViewById
loads resources from a file. It returns some kind of View
, but the Java compiler has no way of knowing that it will be a DrawerLayout
(because it is defined in a file outside of Java's compilation).
If you need it to be a DrawerLayout
in your code, you have to cast it.
That makes sure (at runtime) that it really is such an object (if it is not, you will get a ClassCastException
and your program will abort at that point).
The reason you want to cast it as DrawerLayout
is that you may want to call methods on the instance that are defined in that class. Sometimes, you may be fine with just the signature of the more general superclass. Then you don't have to cast it.
To be sure, the instance returned by findViewById
is a DrawerLayout
no matter if you cast it or not. But if you don't cast it, then Java won't let you treat it as a DrawerLayout
. That is the point of a type-safe language: Unless the compiler can be sure that an object is of a certain class, it won't let you call methods (or access fields) for that class.
In android - while writing java code you need to bring XML code inside Java.
So we use R.id.drawer_layout
is what we want to bring inside java which becomes
findViewById(R.id.drawer_layout)
which returns an Object
.
So we then assign it to a variable declared at top.
private DrawerLayout mDrawerLayout;
where DrawerLayout
is a class in java android.
mDrawerLayout = findViewById(R.id.drawer_layout);
Since findViewById(R.id.drawer_layout)
returns an object and we are assigning it to a variable we need to typecast by using
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);