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).
这篇关于为什么我们不能重写一个方法并将其定义为返回原始方法的超类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我们不能重写一个方法并将其定义为返回原始方法的超类?
基础教程推荐
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
