plz help me in getting the points i'am missing to find why this code does not compile? Code: class SuperBase { } class Base extends SuperBase { } class Derived extends Base { } class CovTest1 { public Derived getIt() { return new Derived(); } } class SubCovTest2 extends CovTest1 { public SuperBase getIt() { return new SuperBase(); } }
Hi Shabir, This code will not compile as Superbase is in higher hierarchy as compared to Derived. You cant narrow the scope but can widen it. you are narrowing the scope of getIt() in derived class, SubCovTest2.
The exception is covariant return (used as of Java 5) This can return a type that is a subclass of what is returned by the overriden method. So in subclass SuperBase return type is not allowed.