I have read in so many blogs that a method's inputs are contravariant and return type is covariant. As for as I understand, both are covariant (where in place of actual type, it's subtype can be given). This can be demonstrated with the below example.
class SuperClass{}
class SubClass extends SuperClass{}
class SubClass1 extends SubClass{}
public class VarianceExample {
public SubClass method(SuperClass ip) {
return new SubClass();
}
public static void main(String[] args) {
new VarianceExample().method(new SubClass());
}
}
In the above code snippet, while calling the 'method()', it's input can be an instance of: SuperClass, SubClass, SubClass1. Similarly, if we change the return type (from new SubClass() ) to new SubClass1(), it works well. In both the scenarios, what is clear is that they are only covariant.
But, if we change the return statement to 'new SuperClass()', compiler throws syntax error. And similarly, if we pass anything which is a superclass of SuperClass (let us assume there is a one; but not in the above code snippet), the compiler will throw error.
Then how can we say that i/p are contravariant and output are covariant ? Both are covariant, Aren't they ?
Can you please help. Thanks!