Polymorphism in Java

In Java, polymorphism refers to the ability of a class to provide different implementations of a method, depending on the type of object that is passed to the method.

If you are inheriting from another class, and you have got a method, and you override that method, that is what polymorphism

package anote;

public class Main {
    public static void main(String[] args) {

        for (int i=1; i<6; i++){
            Movie movie = randomMovie();
            System.out.println("Movie #" + ":" + movie.getName() + "\n" + "Plot: " + movie.plot() + "\n" );
        }
    }

    public static Movie randomMovie(){
        int randomNumber = (int) (Math.random() * 3) + 1;
        System.out.println("Random number generated was: " + randomNumber);
        switch(randomNumber){
            case 1:
                return new Jaws();
            case 2:
                return new LoveLetter();
            case 3:
                return new DoctorStrange();
        }
        return null;
    }
}

class Movie {
    private String name;

    public Movie(String name) {
        this.name = name;
    }

    public String plot() {
        return "No plot here";
    }

    public String getName(){
        return name;
    }
}

class Jaws extends Movie {
    public Jaws() {
        super("Jaws");
    }

    public String plot() {
        return "A shark eats lots of people";
    }
}

class LoveLetter extends Movie {
    public LoveLetter() {
        super("Love Letter");
    }

    @Override
    public String plot() {
        return "Hello, How are you";
    }
}

class DoctorStrange extends Movie {
    public DoctorStrange() {
        super("Doctor Strange");
    }
    // No plot
}
Random number generated was: 3
Movie #:Doctor Strange
Plot: No plot here

Random number generated was: 1
Movie #:Jaws
Plot: A shark eats lots of people

Random number generated was: 2
Movie #:Love Letter
Plot: Hello, How are you

Random number generated was: 3
Movie #:Doctor Strange
Plot: No plot here

Random number generated was: 2
Movie #:Love Letter
Plot: Hello, How are you

Leave a Reply

Your email address will not be published.

ANOTE.DEV