Java Covariant Return Types - The Coding Shala

Home >> Learn Java >> Java Covariant Return Types

Java Covariant Return Types

In Java 5.0 onward it is possible to override a method by changing the return type. The child's return type should be sub-type of parent's return type.
Java Covariant Return Types - The Coding Shala
Covariant return type refers to the return type of an overriding method. It works only for non-primitive return types.

Example of Covariant Return Type in Java

The following is a simple example of the covariant return type is java: 

//covariant return type example 
//thecodingshala.com 

class Parent{
    Parent Display(){
        System.out.println("Inside Parent's Display");
        return this;
    }
}

class Child extends Parent{
    Child Display(){
        System.out.println("Inside Child's Display");
        //can write also
        //return this;
        return new Child();
    }
}

class Main{
    public static void main(String[] args){
        Parent p1 = new Parent();
        p1.Display();
        
        Parent p2 = new Child();
        p2.Display();
    }
}
Output:
Inside Parent's Display
Inside Child's Display

we will see one more example of method overriding that explains covariant return types: 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

//Complete the classes below
class Flower {
    String whatsYourName(){
        return "I have many names and types";
    }
}

class Jasmine extends Flower{
    String whatsYourName(){
        return "Jasmine";
    }
}

class Lily extends Flower{
    String whatsYourName(){
        return "Lily";
    }
}

class Region {
    Flower yourNationalFlower(){
        return new Flower();
    }
}

class WestBengal extends Region{
    Jasmine  yourNationalFlower(){
        return new Jasmine();
    }
}

class AndhraPradesh extends Region{
    Lily yourNationalFlower(){
        return new Lily();
    }
}


public class Solution {
  public static void main(String[] args) throws IOException {
      BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
      String s = reader.readLine().trim();
      Region region = null;
      switch (s) {
        case "WestBengal":
          region = new WestBengal();
          break;
        case "AndhraPradesh":
          region = new AndhraPradesh();
          break;
      }
      Flower flower = region.yourNationalFlower();
      System.out.println(flower.whatsYourName());
    }
}



Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

New Year Chaos Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Method Overloading - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala