RGAlex

Polymorphism

Apr 18th, 2021 (edited)
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.10 KB | None | 0 0
  1. package com.company;
  2.  
  3. class Movie {
  4.     private final String name;
  5.  
  6.     public Movie(String name) {
  7.         this.name = name;
  8.     }
  9.  
  10.     public String plot() {
  11.         return "No plot here";
  12.     }
  13.  
  14.     public String getName() {
  15.         return name;
  16.     }
  17. }
  18.  
  19. class Jaws extends Movie {
  20.     public Jaws() {
  21.         super("Jaws");
  22.     }
  23.  
  24.     public String plot() {
  25.         return "A shark eats lots of people";
  26.     }
  27. }
  28.  
  29. class IndependenceDay extends Movie {
  30.     public IndependenceDay() {
  31.         super("Independence Day");
  32.     }
  33.  
  34.     @Override
  35.     public String plot() {
  36.         return "Aliens attempt to take over planet earth";
  37.     }
  38. }
  39.  
  40. class MazeRunner extends Movie {
  41.     public MazeRunner() {
  42.         super("Maze Runner");
  43.     }
  44.  
  45.     @Override
  46.     public String plot() {
  47.         return "Kids try and escape a maze";
  48.     }
  49. }
  50.  
  51. class StarWars extends Movie {
  52.     public StarWars() {
  53.         super("Star Wars");
  54.     }
  55.  
  56.     @Override
  57.     public String plot() {
  58.         return "Imperial Forces try to take over the universe";
  59.     }
  60. }
  61.  
  62. class Forgettable extends Movie {
  63.     public Forgettable() {
  64.         super("Forgettable");
  65.     }
  66.     // No plot method
  67. }
  68.  
  69. public class Main {
  70.  
  71.     public static void main(String[] args) {
  72.         for (int i = 1; i < 11; i++) {
  73.             Movie movie = randomMovie();
  74.             assert movie != null;
  75.             System.out.println("Movie #" + i +
  76.                     " : " + movie.getName() + "\n" +
  77.                     "Plot: " + movie.plot() + "\n");
  78.         }
  79.     }
  80.  
  81.     public static Movie randomMovie() {
  82.         int randomNumber = (int) (Math.random() * 5) + 1;
  83.         System.out.println("Random number generated was " + randomNumber);
  84.         switch (randomNumber) {
  85.             case 1:
  86.                 return new Jaws();
  87.             case 2:
  88.                 return new IndependenceDay();
  89.             case 3:
  90.                 return new MazeRunner();
  91.             case 4:
  92.                 return new StarWars();
  93.             case 5:
  94.                 return new Forgettable();
  95.         }
  96.         return null;
  97.     }
  98. }
  99.  
Advertisement
Add Comment
Please, Sign In to add comment