为什么我们总是在Android / Java中输入? [英] Why do we always type cast in Android/Java?

查看:101
本文介绍了为什么我们总是在Android / Java中输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Android应用程序,只是很好奇为什么我们必须始终在Android中进行类型转换。我知道我们需要确定类型以便我们的代码正常运行,但也许还有其他原因?

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 properly, but is there, perhaps, another reason?

示例

public class Navigation extends Activity {
    private DrawerLayout mDrawerLayout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // other irrelevant code
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

在这个问题的上下文中,我问为什么我们必须输入 - 返回的返回值findViewById。 (我也很好奇如果可以解释这种类型的铸造是怎么做的。)

In the context of this question, I am asking why we must type-cast the returned value of the findViewById. (I'm also curious how this type casting is done if one could explain that.)

推荐答案

findViewById 从文件加载资源。它返回某种 View ,但Java编译器无法知道它将是 DrawerLayout (因为它是在Java编译之外的文件中定义的。

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).

如果你需要它是一个 DrawerLayout 代码,你必须施展它。
这确保(在运行时)它确实是这样一个对象(如果不是,你会得到一个 ClassCastException ,你的程序将在那时中止)。

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).

您希望将其强制转换为 DrawerLayout 的原因是您可能希望调用实例上的方法在该类中定义的。有时候,你可能只使用更一般的超类的签名就可以了。然后你不必强制转换它。

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.

可以肯定的是, findViewById 返回的实例是 DrawerLayout 无论你是否投了它。但是如果你没有强制转换它,那么Java就不会让你把它当作 DrawerLayout 。这是类型安全语言的要点:除非编译器可以确定某个对象是某个类,否则它不会让你调用该类的方法(或访问字段)。

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.

这篇关于为什么我们总是在Android / Java中输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆