Why in java method overriding allows to have covariant return types, but not covariant parameters?

余生长醉 提交于 2019-12-18 05:56:09

问题


For example I have a Processor base class with a method that returns an Object and takes Object as a parameter. I want to extend it and create a StringProcessor which will return String and take String as parameter. However covariant typing is only allowed with return value, but not parameter. What is the reason for such limitations?

class Processor {
    Object process (Object input) {
        //create a copy of input, modify it and return it
        return copy;
    }
}

class StringProcessor extends Processor {
    @Override
    String process (String input) { // permitted for parameter. why?
        //create a copy of input string, modify it and return it
        return copy;
    }
}

回答1:


The Liskov principle. When designing the Processor class, you write a contract saying: "a Processor is able to take any Object as argument, and to return an Object".

The StringProcessor is a Processor. So it's supposed to obey that contract. But if it only accepts String as argument, it violates that contract. Remember: a Processor is supposed to accept any Object as argument.

So you should be able to do:

StringProcessor sp = new StringProcessor();
Processor p = sp; // OK since a StringProcessor is a Processor
p.process(new Integer(3456));

When returning a String, it doesn't violate the contract: it's supposed to return an Object, a String is an Object, so everything is fine.

You can do what you want to achieve by using generics:

class Processor<T> {
    Object process (T input) {
        //create a copy of input, modify it and return it
        return copy;
    }
}

class StringProcessor extends Processor<String> {
    @Override
    String process (String input) { 
        return copy;
    }
}



回答2:


Also, if you want a type-theoretical answer, the reason for this is, when considering the subtyping relation on function types, the relation is covariant on return types, but contravariant on argument types (i.e. X -> Y is a subtype of U -> W if Y is a subtype of W and U is a subtype of X).



来源:https://stackoverflow.com/questions/46861804/why-in-java-method-overriding-allows-to-have-covariant-return-types-but-not-cov

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!