We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Java
- Advanced
- Covariant Return Types
- Discussions
Covariant Return Types
Covariant Return Types
Sort by
recency
|
101 Discussions
|
Please Login in order to post a comment
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;
//Complete the classes below class Flower { String whatsYourName(){
}
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()); } }
I am use abstract class:
abstract class Flower { public abstract String whatsYourName(); }
class Jasmine extends Flower {
}
class Lily extends Flower {
}
abstract class Region { public abstract Flower yourNationalFlower(); }
class WestBengal extends Region {
}
class AndhraPradesh extends Region {
}
Maybe I missed the point, but I didn't see a reason to recreate the metho in each subclass.
The class diagram provided has an error in it; the Lotus class depicted as extending Flower should actually be named (and return) "Lily". The provided code correctly has a Lily class instead of a Lotus class.