Video in progress

What is polymorphism? Show it with a simple example.

Polymorphism means working with different objects through a single type (an interface or a parent class). Which version of a method runs is decided at runtime by the actual type of the object.

📖 Answer

interface Notifier { void send(String to, String text); }

class SmsNotifier implements Notifier {
    public void send(String to, String text) { /* SMS gateway */ }
}
class TelegramNotifier implements Notifier {
    public void send(String to, String text) { /* Bot API */ }
}

void notifyAll(List<Notifier> channels, String to, String text) {
    for (Notifier n : channels) {
        n.send(to, text);   // which send runs is decided at runtime
    }
}

The notifyAll method doesn't change when a new channel (say, email) is added; you just write a new class. That is the whole point of polymorphism.

In Java people usually mention two kinds:

  • runtime, through overriding, as in the example above; the JVM finds the right version with a virtual method call;
  • compile-time, through overloading: methods with the same name but different parameters; the compiler decides which one is called.

In an interview they usually expect the first one, and mentioning the second as an extra is enough.