gpt4 book ai didi

java - 将子类对象转换为父类(super class)

转载 作者:行者123 更新时间:2023-11-30 09:18:20 25 4
gpt4 key购买 nike

我有一些关于 upcast/downcast 的问题。

我创建了一个抽象父类(super class) Animal、子类 Dog 和子类 BigDog。我还在 Animal 中提供抽象方法,并在 Dog 和 BigDog 中覆盖它。

abstract public class Animal {
abstract public void greeting();
}

public class Dog extends Animal {
@Override
public void greeting() {
System.out.println("Woof!");
}
}

public class BigDog extends Dog {
@Override
public void greeting() {
System.out.println("Woow!");
}
}

现在我的测试代码:

public class TestAnimal {
public static void main(String[] args) {

Animal animal2 = new Dog();
Animal animal3 = new BigDog();

// Downcast
Dog dog2 = (Dog) animal2; //cast Animal class to Dog class, legit
BigDog bigDog2 = (BigDog) animal3; //cast Animal to BigDog, legit;
Dog dog3 = (Dog) animal3; //Animal Class contains BigDog cast into Dog?
dog2.greeting();
dog3.greeting(); //in which class the method is called?
}
}

我了解父类(super class)/子类之间的关系以及转换的工作原理。但是,我的问题是,如果知道中间有一个类,您能否将一个父类(super class)转换为一个特定的子类?例如,如果我有一个包含 BigDog 对象的 Animal 类对象,我可以将该对象转换为 Dog 吗?如果 BigDog 中有 Dog 中不存在的方法怎么办?

简而言之,你当然可以说一个父类(super class)对象是一个子类对象,但为什么可以倒置呢?


再想想,

我猜是这样的:我要求 JVM 将 Animal 类引用转换为 Dog 并将新的 Dog 引用链接到 BigDog 对象,而不是真正转换 BigDog 对象。

所以我可以调用该 Dog 引用(对 BigDog)的所有 Dog 和 Animal 方法,但不能调用任何 BigDog 方法,除非它在 ​​BigDog 中被覆盖。

Java 在调用方法时检查的是:引用 (DOG) 是否有引用,对象 (BigDog) 是否有覆盖。如果不是,则调用 Dog 方法,否则,将调用 BigDog 方法。

谁能证实我的猜测?

最佳答案

您始终可以转换为特定的子类,除非编译器足够聪明,可以确定您的转换是不可能的。

转换到子类的最好方法是检查它是否可以完成:

  if ( doggy instanceof BigDog ) {
doSomethingWithBigdog( (BigDog) doggy );
} else if ( doggy instanceof SmallDog ) {
doSomethingWithSmalldog( (SmallDog) doggy );
} else {
// Neither a big dog nor a small dog
}

...

private void doSomethingWithBigdog( BigDog dog ) {
...
}

private void doSomethingWithSmalldog( SmallDog dog ) {
...
}

请记住,类型转换是邪恶的。有时是必要的,但通常(并非总是)它可以通过在基类上实现方法来设计,或者通过不将 Dog 分配给 Animal 变量而是将其保留为 Dog。

关于java - 将子类对象转换为父类(super class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18530321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com