将对象从父类转换为子类 [英] Typecasting an object from parent class to child
问题描述
我对用Java语言进行类型转换有误解.问题是 ClassCastException .例如,在此代码中,假设Animal是Dog类的父类,
I have a misunderstanding about typecasting in Java language. The problem is ClassCastException. For example, in this code, assuming Animal is the parent class of the Dog class,
Animal animal = new Animal();
Dog dog = (Dog) animal;
在执行后引发 ClassCastException . 但是,在研究android程序包时,考虑到该Java示例,我发现了一个有关类型转换的示例,该示例应抛出 ClassCastException .
throws ClassCastException after execution. However, while studying android packages, I found an example about typecasting which should throw a ClassCastException, considering that java example.
EditText editText = (EditText) findViewById(R.id.edit_message);
在此代码中, findViewById 方法返回一个 View 类对象,该对象是 EditText 类的超类之一. > android.view.View 到 android.widget.EditText ),代码运行正常.谁能解释我是否犯了错或如何发生?
In this code, findViewById method returns a View class object, which is one of the superclasses of EditText class.(from android.view.View to android.widget.EditText) The code runs fine. Could anyone explain if I made a mistake or how this happens?
提前谢谢.
推荐答案
创建对象后,就无法更改其类型.这就是为什么您不能将动物投向狗的原因.
Once you create an object, you can't change its type. That's why you can't cast an Animal to a Dog.
但是,如果创建子类的对象,则可以在超类类型的变量中保留对它的引用,以后再将其强制转换为子类类型.
However, if you create an object of a sub-class, you can keep a reference to it in a variable of the super-class type, and later you can cast it to the sub-class type.
这将起作用:
Animal a = new Dog ();
Dog d = (Dog) a;
在Android示例中,您具有一个如下所示的布局资源:
In the Android example, you have a layout resource that looks like this :
<EditText
android:id="@+id/edit_message"
..."/>
此定义将导致Android创建EditText
的实例,因此您可以将findViewById
返回的视图强制转换为EditText
.您不能将其强制转换为不是EditText
超级类型的其他任何对象.
This definition will cause Android to create an instance of EditText
, and therefore you can cast the view returned by findViewById
to EditText
. You can't cast it to anything else that isn't a super-type of EditText
.
这篇关于将对象从父类转换为子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!