I have a subclass named child which inherits a class named parent. I am trying to override the method in the super class. I have experimented a little. I have created the overriden method with its return type short which is the subtype of int. As far I know I can do so. And the method is legally overriden. whenever I call the method with the reference of the super class, the compiler generates an incompatible return type error. What’s the problem here ? My code is given below:
class parent
{
int test()
{
System.out.println("called inside parent\n");
return 1;
}
}
class child extends parent
{
short test()
{
System.out.println("called inside child\n");
return 1;
}
}
class Myclass
{
public static void main(String[] args)
{
parent a=new child();
a.test();
}
}
Wrong, it is not. The value range of
shortis a subset of that ofint, but this is a totally different issue. Ashortvalue can indeed be converted to anint(even implicitly), still ashortis not anint.Primitive types are not regular classes, so these can’t have supertype/subtype relationships. Therefore you can’t use contravariance of return type in this case: once you declared a return type of
intin the base method, all of its overrides must returnint.