why we can#39;t override a method and define it to return a superclass of the original method?(为什么我们不能重写一个方法并将其定义为返回原始方法的超类?)
问题描述
我目前正在从 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).
这篇关于为什么我们不能重写一个方法并将其定义为返回原始方法的超类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我们不能重写一个方法并将其定义为返回原始方法的超类?
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01