想象一下是否有可能:
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!
}
}
瞧,这只是合同问题。当您去咖啡店时,您期望它可以出售咖啡。如果不遵守此合同,则不能将其称为“咖啡店”:咖啡店必须出售咖啡。它可以出售牛奶咖啡,因为牛奶咖啡仍然是咖啡。(就像汽车制造厂只能生产丰田汽车一样,因为丰田汽车是一辆汽车,您可以像其他任何一辆汽车一样驾驶丰田汽车,甚至不知道它是丰田汽车 :这就是多态性。)