java - why short is incompatible to int in the context of overriding? -
i have subclass named child inherits class named parent. trying override method in super class. have experimented little. have created overriden method return type short subtype of int. far know can so. , method legally overriden. whenever call method reference of super class, compiler generates incompatible return type error. what's problem here ? code 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(); } }
short subtype of int
wrong, not. value range of short subset of of int, totally different issue. short value can indeed converted to int (even implicitly), still short is not int.
primitive types not regular classes, these can't have supertype/subtype relationships. therefore can't use contravariance of return type in case: once declared return type of int in base method, of overrides must return int.
Comments
Post a Comment