如何向下转换Java对象? [英] How to downcast a Java object?

查看:92
本文介绍了如何向下转换Java对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解Java的多态性,我有一个关于向下转换对象的问题。
让我们说这个例子我有两个子类Dog和Cat继承自超类Animal

I am trying to understand Java's polymorphism, and I have one question about downcasting an object. Let's say for this example I have two subclasses Dog and Cat that inherit from a superclass Animal

从我的理解,向下转换对象的唯一方法是如果这个Object已经是好的类型,如下所示:

From what I understood, the only way to downcast an object is if this Object is already of the good type, like this:

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

这适用吗?

但是如果我想在不知道它的情况下制作一只普通的动物,然后在我知道的时候施放它,我该怎么做?

But what if I want to create a regular animal without knowing what it would be, and then cast it when I know, how can I do that?

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

这会在运行时抛出ClassCastException吗?

This will throw a ClassCastException at runtime right?

我发现这样做的唯一方法是创建一个新的Dog构造函数,用于创建常规动物的狗:

The only way I found to do that is to create a new Dog constructor that creates a dog from a regular animal:

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

with

public Class Dog extends Animal{
   public Dog(Animal a){
      super(a);
   }
}

所以我的问题是,我该怎么做这个?

So my question is, how am I supposed to do this?


  • 我这样做是最好的方式吗?

  • 我不应该这样做总而言之,如果我不得不这意味着我的计划没有得到很好的设想?

  • 我错过了更好的方式吗?

非常感谢!
nbarraille

Thanks a lot! nbarraille

推荐答案

如果要创建可能因非本地条件而异的类型实例,使用抽象工厂(如设计模式一书中所述)。

If you want to create an instance of a type that may vary depending upon non-local conditions, use an Abstract Factory (as described in the Design Patterns book).

以最简单的形式:

interface AnimalFactory {
    Animal createAnimal();
}

class DogFactory implements AnimalFactory {
    public Dog createAnimal() {
        return new Dog();
    }
}

注意静态类型之间也有区别引用和对象的动态类型。即使您有 Animal 引用,如果原始对象是 Dog ,它仍然表现得像

Note also there is a difference between the static type of a reference and the dynamic type of the object. Even though you have an Animal reference, if the original object is a Dog, it still behaves like a Dog.

这篇关于如何向下转换Java对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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