Liskov Substitution

Liskov substitution means that parent classes should be able to be switched to child classes and all code should continue to function. The parent can be any kind of interface, abstract class or class.

We go look at an example of Liskov substitution with a monster interface and 2 monsters.
Monster

public interface Monster {
    String attack();
}

Vampire

public class Vampire implements Monster {
    @Override
    public String attack() {
        return "The vampire attacked";
    }
}

Werewolf

public class Werewolf implements Monster {
    @Override
    public String attack() {
        return "The werewolf attacked";
    }
}

Main

public static void main(String[] args) {
    Monster m = new Vampire();
    System.out.println(m.attack());

    m = new Werewolf();
    System.out.println(m.attack());
}

We instantiate a vampire which is a implementation of monster. Because a monster can be switched with any child of a monster we can switch a vampire to a werewolf.

Liskov substitution is the mathematical principle that enable polymorphic behavior in OOP.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s