In OCP book I have read that there is this rule for covariance:
Given an inherited return type A and an overriding return type B, can you assign an instance of B to a reference variable for A without a cast? If so, then they are covariant. This rule applies to primitive types and object types alike.
If the rule applies to primitive types and I can assign int value to long variable without a cast (so they are covariant) then why the code does not compile (covariant return types)? I assume there is something wrong with this sentence or with my understanding of it?
class Class1
{
long method()
{
return 1L;
}
}
class Class2 extends Class1
{
public static void main(String[] args)
{
int B = 1;
long A = B; // no cast
}
// @Override
// int method() { return 1; } // does not compile // 'method()' in 'B' clashes with 'method()' in 'A'; attempting to use incompatible return type
}