简体   繁体   中英

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

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

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

另外,如果你想要一个类型理论答案,其原因是,当考虑函数类型的子类型关系时,关系在返回类型上是协变的,但在参数类型上是逆变的 (即X -> YU -> W的子类型) U -> W如果Y是的子类型WU是的子类型X )。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM