为什么我们不能重写一个方法并将其定义为返回原始方法的超类?

2022-01-19 00:00:00 return subclass overriding java

我目前正在从 Java 教程 oracle<中学习 Java 类和对象/a> 并遇到了以下语句和代码.我理解这个概念,但我不知道为什么我们不能重写一个方法并将其定义为返回原始方法的超类?背后的原因是什么?有人可以启发我吗?提前感谢您的帮助!

I'm currently learning Java classes and objects from java tutorial oracle and have encountered the following statements and code. I understand the concept but I do not know why we can't override a method and define it to return a superclass of the original method? What is the reason behind it? Could someone please enlighten me? Thanks in advance for any help!

你可以重写一个方法并定义它来返回一个子类原来的方法,像这样:

You can override a method and define it to return a subclass of the original method, like this:

public Number returnANumber() {
    ...
}

覆盖原来的方法:

public ImaginaryNumber returnANumber() {
    ...
}

推荐答案

想象一下,如果可能的话:

Imagine if it was possible:

public class CarFactory {
    Car giveMeACar() { ... };
}

public class SpecialCarFactory extends CarFactory {
    @Override
    Object giveMeACar() {
        return "hello world";
    }
)

public class Driver {
    void drive() {
        CarFactory carFactory = new SpecialCarFactory();

        Car car = carFactory.giveMeACar();
        // err, wait, sorry, can't do that. 
        // This car factory, despite its name, doesn't produce cars. 
        // It produces objects, and I've heard they're just 
        // "hello world" strings. Good luck driving a "hello world"
        // string on a highway!
    }
}

看,这只是合同的事情.当你去咖啡店时,你希望它卖咖啡.不遵守本合同的东西不能称为咖啡店":咖啡店必须卖咖啡.它可以出售挤奶咖啡,因为挤奶咖啡仍然是咖啡.(就像汽车厂只能生产丰田,因为丰田是一辆汽车,你可以像驾驶其他汽车一样驾驶丰田,甚至不知道它是丰田:这就是多态性.

See, it's just a contract thing. When you go to a coffee shop, you expect it to sell coffee. Something can't be called "a coffee shop" if it doesn't comply to this contract: a coffee shop must sell coffee. It can sell milked coffee, because a milked coffee is still a coffee. (just like a car factory can produce Toyota only, because Toyota is a car, and you can drive a Toyota like any other car, without even knowing it's a Toyota: that's polymorphism).

相关文章