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:
- public Number returnANumber() {
- …}
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
- public ImaginaryNumber returnANumber() {
- …}
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..
- import java.lang.Number;
- class ImaginaryNumber extends Number {
- @Override
- public int intValue() {
- throw new UnsupportedOperationException(“Not supported yet.”);
- }
- @Override
- public long longValue() {
- throw new UnsupportedOperationException(“Not supported yet.”);
- }
- @Override
- public float floatValue() {
- throw new UnsupportedOperationException(“Not supported yet.”);
- }
- @Override
- public double doubleValue() {
- throw new UnsupportedOperationException(“Not supported yet.”);
- }
- }
- class Myclass extends ImaginaryNumber {
- public ImaginaryNumber returnANumber() {
- ImaginaryNumber n1 = null;
- return n1;
- }
- public Number returnANumber2() {
- Number n1 = null;
- return n1;
- }
- public Number returnANumber3() {
- ImaginaryNumber n1 = null;
- return n1;
- }
- public static void main(String[] args) {}
- }