为什么我们不能重写方法并定义它以返回原始方法的超类? [英] why we can't override a method and define it to return a superclass of the original method?
问题描述
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() {
...
}
推荐答案
想象一下是否有可能:
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).
这篇关于为什么我们不能重写方法并定义它以返回原始方法的超类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!