Skip to main content

Covariant methods

Normally when we override a function(method) in a derived class, this overriding function must have the same signature as the function in base class.

But in Java, the overriding method can have a different return type provided this return type is the sub-class of return type in overridden method. Such methods are called Covariant methods.

e.g
class Ret1{....}
class B
{
    Ret1 foo(int n){
      .......
    }
}
class Ret2 extends Ret1{.....}
class C extends B{
     Ret2 foo(int n){
        ....
    }
}


In the derived class C, we are overriding the function foo. Return type of foo() in base class is Ret1 and return type of foo() in derived class is Ret2. This is valid because, Ret2 is a sub-class of Ret1.


Let us look at a complete example.

class Number{
    Number(int n)
    {
      this.n = n;
    }
    int n;
}
class SmallNumber extends Number{
   byte  n;
   SmallNumber(byte  n)
   {
       super(n);            
       this.n = n;
   }
}
class Covar {
    Number findSquare(int n)
   {
      int s = n*n;
      Number obj = new Number(s);
      return obj;
   }
}
class CovarSub extends Covar{
    SmallNumber findSquare(int n)
    {
        SmallNumber obj = new SmallNumber((byte)(n*n));
        return obj           ;
    }
    public static void main(String args[]){
      CovarSub cs1 = new CovarSub();
      SmallNumber sn = cs1.findSquare(10);
      System.out.println("Ouput is "+sn.n);
      }
}

 Here SmallNumber is a subclass of Number. Covar class has a function findSquare which returns Number object. And its subclass CovarSub overrides the function findSquare and returns SmallNumber object instead of Number object.
 

Comments