Wednesday 19 February 2014

Covariant return type

An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type.

Example
class Animal{
 String name;

 void setName(String name){
  this.name = name;
 }

 Animal getAnimal(){
  return this;
 }
}

class Tiger extends Animal{
 String name;

 void setName(String name){
      this.name = name;
 }

 Tiger getAnimal(){
      System.out.println("I am tiger and my Name is " + name);
      return this;
 }

 public static void main(String args[]){
      Animal anim = new Tiger();
      anim.setName("Aslam");
      anim.getAnimal();
 }
}

Output
I am tiger and my Name is Aslam

As you see the Tiger.java, the return type for the getAnimal() is Tiger, which is a sub class of “Animal”, so the method overridden.

Some points to Remember

1. Covariant types are applicable for reference types, not for primitives
class Animal{
 int getAnimal(){
  return 0;
 }
}

class Tiger extends Animal{
 byte getAnimal(){
  return 0;
 }
}
     
When you tries to compile the class “Tiger”, compiler throws below error
Tiger.java:2: error: getAnimal() in Tiger cannot override getAnimal() in Animal
byte getAnimal(){
^
return type byte is not compatible with int
1 error


Method Overriding                                                 Hiding methods                                                 Home

No comments:

Post a Comment