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

2

10

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;
    }
}
Obstruction answered 21/10, 2017 at 9:19 Comment(0)
R
19

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;
    }
}
Riccardo answered 21/10, 2017 at 9:24 Comment(0)
I
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).

Impatiens answered 21/10, 2017 at 12:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.