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).
这篇关于为什么我们不能重写一个方法并将其定义为返回原始方法的超类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我们不能重写一个方法并将其定义为返回原始方法的超类?
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01