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.
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
Comments
Post a Comment