Method Overriding rules!!!

shyam_oec's Avatar, Join Date: Nov 2007
Contributor
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
0
xs2vipin.bansal's Avatar, Join Date: Apr 2010
Newbie Member
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.
0
SripatiDas's Avatar, Join Date: Mar 2011
Newbie Member
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.