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).
这篇关于为什么我们不能重写一个方法并将其定义为返回原始方法的超类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我们不能重写一个方法并将其定义为返回原始方法的超类?
基础教程推荐
- Maven:无效的目标版本:10 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
