Covariant return type

Covariant return type Means

 
Hi friend
  
We have return type in our methods, but what is covariant return type?
 
Let’s have an example.
 
Suppose that you have a class hierarchy in which Object is a superclass of java.lang.Number, which is, in turn, a superclass of ImaginaryNumber.
 
The class hierarchy for ImaginaryNumber


Object -> java.lang.Number -> ImaginaryNumber

 
Now suppose that you have a method declared to return a Number:
  1. public Number returnANumber() {  
  2.  …}   
The returnANumber method can return an ImaginaryNumber but not an Object. ImaginaryNumber is a Number because it’s a subclass of Number. However, an Object is not necessarily a Number — it could be a String or another type. You can override a method and define it to return a subclass of the original method, like this
  1. public ImaginaryNumber returnANumber() {  
  2.  …}   
Above means that we can return the same or subclass type as the return type but not superclass type and this is called “covariant return type.” 
 
Following is the .java file of code with explanation..
  1. import java.lang.Number;  
  2. class ImaginaryNumber extends Number {  
  3.  @Override  
  4.  public int intValue() {  
  5.   throw new UnsupportedOperationException(“Not supported yet.”);  
  6.  }  
  7.  @Override  
  8.  public long longValue() {  
  9.   throw new UnsupportedOperationException(“Not supported yet.”);  
  10.  }  
  11.  @Override  
  12.  public float floatValue() {  
  13.   throw new UnsupportedOperationException(“Not supported yet.”);  
  14.  }  
  15.  @Override  
  16.  public double doubleValue() {  
  17.   throw new UnsupportedOperationException(“Not supported yet.”);  
  18.  }  
  19. }  
  20. class Myclass extends ImaginaryNumber {  
  21.  public ImaginaryNumber returnANumber() {  
  22.   ImaginaryNumber n1 = null;  
  23.   return n1;  
  24.  }  
  25.  public Number returnANumber2() {  
  26.   Number n1 = null;  
  27.   return n1;  
  28.  }  
  29.  public Number returnANumber3() {  
  30.   ImaginaryNumber n1 = null;  
  31.   return n1;  
  32.  }  
  33.  public static void main(String[] args) {}  
  34. }