Java 将对象从父类类型转换为子类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25193029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:50:22  来源:igfitidea点击:

Typecasting an object from parent class to child

javaandroidtypescastingpolymorphism

提问by mwb

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,

我对 Java 语言的类型转换有误解。问题是ClassCastException。例如,在这段代码中,假设 Animal 是 Dog 类的父类,

Animal animal = new Animal();
Dog dog = (Dog) animal;

throws ClassCastExceptionafter execution. However, while studying android packages, I found an example about typecasting which should throw a ClassCastException, considering that java example.

执行后抛出ClassCastException。然而,在研究 android 包时,我发现了一个关于类型转换的例子,考虑到那个 java 例子,它应该抛出ClassCastException

EditText editText = (EditText) findViewById(R.id.edit_message);

In this code, findViewByIdmethod returns a Viewclass object, which is one of the superclasses of EditTextclass.(from android.view.Viewto android.widget.EditText) The code runs fine. Could anyone explain if I made a mistake or how this happens?

在这段代码中,findViewById方法返回一个View类对象,它是EditText类的超类之一。(从android.view.Viewandroid.widget.EditText)代码运行良好。谁能解释一下我是否犯了错误或这是如何发生的?

Thanks in advance.

提前致谢。

采纳答案by Eran

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.

但是,如果创建子类的对象,则可以在超类类型的变量中保留对它的引用,然后可以将其强制转换为子类类型。

This will work :

这将工作:

Animal a = new Dog ();
Dog d = (Dog) a;

In the Android example, you have a layout resource that looks like this :

在 Android 示例中,您有一个如下所示的布局资源:

<EditText
    android:id="@+id/edit_message"
 ..."/>

This definition will cause Android to create an instance of EditText, and therefore you can cast the view returned by findViewByIdto EditText. You can't cast it to anything else that isn't a super-type of EditText.

此定义将导致 Android 创建 的实例EditText,因此您可以将返回的视图转换findViewByIdEditText。您不能将其强制转换为不是EditText.

回答by Ritchie Borja

Basically you can't cast an instance of a superclass to a subclass because the instance of a subclass is not yet known. Upcasting is a sure way to prevent this exception to happen because we are now dealing polymorphism to our code.

基本上你不能将超类的实例转换为子类,因为子类的实例尚不清楚。Upcasting 是防止这种异常发生的可靠方法,因为我们现在正在处理代码的多态性。

You must instance a subclass first:

您必须先实例化一个子类:

Dog dog = new Dog;

We can hide the methods of the class Dog not found to its parent class Animal by casting it to its superclass:

我们可以将未找到的 Dog 类的方法隐藏到其父类 Animal 中,方法是将其转换为超类:

Animal animal = (Animal) dog;

Then you can downcast this back to your subclass Dog because the instance of its subclass is already known:

然后你可以将它向下转换回你的子类 Dog 因为它的子类的实例是已知的:

Dog anotherDog = (Dog) animal;

回答by Yash

You can try this:

你可以试试这个:

Base obj= new Derived();
Derived obj2= (Derived)obj;

Hope this will help.

希望这会有所帮助。

回答by Bishwajit Vikram

public class OverridingConcept {
    public static void main(String[] args) {
        // Up-Casting
        Parent p = new Child();
        Child c = (Child) p;
        c.eat();
    }
}
class Parent {
    void show() {
        System.out.println("Parent.Show");
    }
    void eat() {
        System.out.println("Parent.Eat");
    }
}
class Child extends Parent {
    void show() {
        System.out.println("Child.Show");
    }
    void sing() {
        System.out.println("Child.Sing");
    }
}