Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/forums/java/)
-   -   Method Overriding rules!!! (http://www.go4expert.com/forums/method-overriding-rules-t8880/)

shyam_oec 17Feb2008 02:59

Method Overriding rules!!!
 
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();
  }

}


xs2vipin.bansal 30Apr2010 12:17

Re: Method Overriding rules!!!
 
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.

SripatiDas 7Mar2011 12:17

Re: Method Overriding rules!!!
 
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.


All times are GMT +5.5. The time now is 01:55.