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;
}
}
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With