Pages

Covariant return type in Java

Before Java 5.0, when you override a method, both parameters and return type must match exactly.

In Java 5.0, it introduces a new facility called covariant return type.
You can override a method with the same signature but returns a subclass of the object returned.

Case 1: If the return type is void or primitive then the data type of parent class method and overriding method must be same. e.g. if return type is int, float, double then it should be same

public class Fruit {

 int size;

 int description() {
  
  
  return size;

 }

}
public class Apple extends Fruit {

 float size ;

 
 @Override
 float description() {

  
  return size;

 }

}
 
Output
Error : The return type is incompatible with Fruit.description()
 
Case 2: If the return type of the parent class method is derived type then the return type of the overriding method is same derived data type or sub class to the derived data type.

e.g. Suppose you have a class Fruit, Apple is subclass to Fruit, 

public class Fruit {

 String name = "Fruit";

 Fruit description() {
  
  Fruit fruit = new Fruit();
  return fruit;

 }

}
public class Apple extends Fruit {

 String name = "Apple";

 // overiding Fruit class method using subclass type
 @Override
 Apple description() {

  Apple apple = new Apple();

  return apple;

 }

}

No comments:

Post a comment