Why do we always type cast in Android/Java?

前端 未结 3 1561
小蘑菇
小蘑菇 2021-01-04 10:47

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

3条回答
  •  孤独总比滥情好
    2021-01-04 11:08

    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 DrawerLayouts. If you don't cast it, you can't use any of those DrawerLayout methods; you can only use the methods defined for all Views.

    The type-casting doesn't do anything, really. findViewById is declared to return a View, since it can return all different kinds of Views. 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.

提交回复
热议问题