Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

covariant

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;
    }
}
like image 464
user2992672 Avatar asked Oct 21 '17 09:10

user2992672


Video Answer


2 Answers

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;
    }
}
like image 100
JB Nizet Avatar answered Oct 17 '22 09:10

JB Nizet


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).

like image 22
Piotr Wilkin Avatar answered Oct 17 '22 10:10

Piotr Wilkin