Covariant Return Types HackerRank solution in Java
Java allows for Covariant Return Types, which means you can vary your return type as long you are returning a subclass of your specified return type.
Learn more about Method Overriding and Covariant Return Types with Examples :
The name comes from the fact that the type of the return is allowed to vary in the same direction that you subclass.
See problem description on HackerRank :
Lets see solution.
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());
}
}
Happy Coding.
Comments
Post a Comment