Covariant return types in Java programming.

Java 8Object Oriented ProgrammingProgramming

If two classes are in an inheritance relation i.e. if one class extends the other, a copy of superclass members Is created in the subclass. If both super and subclasses have the same methods say sample(), to the subclass object, both methods are available.

Now, if you invoke it using the subclass object the body of that method in the subclass gets executed overriding the superclass method.

Example

 Live Demo

class Super{
   public void demo() {
      System.out.println("This is the method of the superclass");
   }
}
public class Sub extends Super{
   public void demo() {
      System.out.println("This is the method of the subclass");
   }
   public static void main(String args[]){
      Sub sub = new Sub();
      sub.demo();
   }
}

Output

This is the method of the subclass

Covariant return types

Till Java5 for the subclass method to override the super class’s both methods should have the same name arguments and return type too.

But, since Java5 in overriding, it is not mandatory for the methods in the superclass and subclass to have the same return type. These two methods can have different return types but, the method in the subclass should return the subtype of the return type of the method in the superclass. Thus overriding methods become variant with respect to return types and, these are known as co-variant return types.

Example

If you observe the following example superclass has a method named demo() and it returns a value of the type Number. The method in the subclass can return a value of the type Integer which is the subtype of the Number. This sub type (Integer) is known as the covariant type.

 Live Demo

class Super{
   public Number demo(float a, float b) {
      Number result = a+b;
      return result;
   }
}
public class Sub extends Super{
   public Integer demo(float a, float b) {
      return (int) (a+b);
   }
   public static void main(String args[]){
      Sub sub = new Sub();
      System.out.println(sub.demo(25.5f, 89.225f));
   }
}

Output

114

Example

class Example{
   int data =100;
   Example demoMethod(){
      return this;
   }
}
public class Sample extends Test{
   int data =1000;
   Sample demoMethod(){
      return this;
   }
   public static void main(String args[]){
      Sample sam = new Sample();
      System.out.println(sam.demoMethod().data);
   }
}

Output

1000
raja
Published on 06-Sep-2019 12:52:50
Advertisements