您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

为什么我们不能重写方法并定义它以返回原始方法的超类?

为什么我们不能重写方法并定义它以返回原始方法的超类?

想象一下是否有可能:

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!
    }
}

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

其他 2022/1/1 18:30:40 有482人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶