HackerRank Java- Covariant Return Types




You will be given a partially completed code in the editor where the main method takes the name of a state (i.e., WestBengal, or AndhraPradesh) and prints the national flower of that state using the classes and methods written by you.



  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. class Flower {
  5. String whatsYourName() {
  6. return "I have many names and types.";
  7. }
  8. }
  9. class Jasmine extends Flower {
  10. @Override
  11. String whatsYourName() {
  12. return "Jasmine";
  13. }
  14. }
  15. class Lily extends Flower {
  16. @Override
  17. String whatsYourName() {
  18. return "Lily";
  19. }
  20. }
  21. class Region {
  22. Flower yourNationalFlower() {
  23. return new Flower();
  24. }
  25. }
  26. class WestBengal extends Region {
  27. @Override
  28. Jasmine yourNationalFlower() {
  29. return new Jasmine();
  30. }
  31. }
  32. class AndhraPradesh extends Region {
  33. @Override
  34. Lily yourNationalFlower() {
  35. return new Lily();
  36. }
  37. }
  38. public class Solution {
  39. public static void main(String[] args) throws IOException {
  40. BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  41. String s = reader.readLine().trim();
  42. Region region = null;
  43. switch (s) {
  44. case "WestBengal":
  45. region = new WestBengal();
  46. break;
  47. case "AndhraPradesh":
  48. region = new AndhraPradesh();
  49. break;
  50. }
  51. Flower flower = region.yourNationalFlower();
  52. System.out.println(flower.whatsYourName());
  53. }
  54. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube