1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Method Overriding rules!!!

Discussion in 'Java' started by shyam_oec, Feb 16, 2008.

  1. shyam_oec

    shyam_oec New Member

    Joined:
    Nov 26, 2007
    Messages:
    89
    Likes Received:
    1
    Trophy Points:
    0
    Occupation:
    Software Developer, .NET Framework
    Location:
    Jamshedpur
    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 a moderator: Mar 7, 2011
  2. xs2vipin.bansal

    xs2vipin.bansal New Member

    Joined:
    Apr 30, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    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.
     
  3. SripatiDas

    SripatiDas New Member

    Joined:
    Mar 7, 2011
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    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.
     

Share This Page