为什么从孩子到父母的强制转换是不可能的

发布于 2025-01-16 20:11:57 字数 591 浏览 4 评论 0原文

我有一个动物类,其中有一个孩子狗。

class Animal {
    public void makeSound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    @Override
    public void makeSound() {
        super.makeSound();
    }
}

public static void main(String[] args) {
    Dog dog = (Dog) new Animal(); // It compiles, but throws runtime exception.
    dog.makeSound();
}

在这里,如果我们将子对象转换为父对象,它将编译,但会抛出运行时异常 - ClassCastException。当然,可能存在子级具有父级没有的字段或方法的情况。这就是为什么我们不能将 Dog 转换为 Animal。而且,不存在 IS-A 关系。但是,如果父类和子类只有相同的字段和方法,为什么强制转换是不可能的?
我在采访中被问到这个问题)

谢谢。

I have a class Animal which has one child Dog.

class Animal {
    public void makeSound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    @Override
    public void makeSound() {
        super.makeSound();
    }
}

public static void main(String[] args) {
    Dog dog = (Dog) new Animal(); // It compiles, but throws runtime exception.
    dog.makeSound();
}

Here if we will cast child to parent, it will compile, but it will throw runtime exception - ClassCastException. Of course, there can be a case when the child will have a field or method which the parent doesn't. That's why we can't cast Dog to Animal. Also, there's no IS-A relationship. But why the cast is not possible, in case parent and child classes have only the same fields and methods?
I've got asked this question in the interview)

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沫雨熙 2025-01-23 20:11:57

当编译器发现您尝试将 Animal 对象转换为 Dog 时,它“知道”Dog 在层次结构中位于 Animal 之下,因此该动物可能是狗,因此它允许这样做。然而,在运行时,事实证明它只是一个动物,而不是一个狗,所以转换失败。

这是一个奇怪的情况,在阅读程序时很明显动物只是一个动物而不是狗,因为它只是用“new Animal()”创建的,但编译器不知道这一点——它只是知道它是一种动物。编译器很聪明,但他们不可能知道一切。我希望这是有道理的。

When the compiler sees that you are trying to cast the Animal object into a Dog, it "knows" that Dog is underneath Animal in the hierarchy, so it is possible that the animal is a dog, so it allows it. However, at runtime, it turns out that it is just an Animal, and is not a Dog, so the cast fails.

This is a weird case in which it is obvious in reading the program that the Animal is just an Animal and not a Dog because it was just created with "new Animal()", but the compiler doesn't know that--it just knows that it is an Animal. Compilers are smart, but they can't know everything. I hope that makes sense.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文