Method Overriding rules!!!

Contributor
17Feb2008,02:59   #1
shyam_oec's Avatar
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();
  }

}

Last edited by shabbir; 7Mar2011 at 12:29.. Reason: Code blocks
Newbie Member
30Apr2010,12:17   #2
xs2vipin.bansal's Avatar
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.
Newbie Member
7Mar2011,12:17   #3
SripatiDas's Avatar
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.