Search Sreeni's Insights

Filter by content type
technical September 6, 2011 13 min read

What are subtype and subclass polymorphism? - Part 6

This article explains polymorphism through cash, card, wallet and discount examples, comparing subclass and subtype polymorphism and showing why substitutability matters in design for billing software.

Share:

What are subtype and subclass polymorphism? - Part 6

Our shop started with cash payment only. Then the card machine came, then the mobile wallet, and next year there may be something else. Same with discounts, festival offer, loyalty points, bulk purchase, staff discount. If the billing code checks “if cash do this, else if card do that, else if wallet…” in every place, each new payment type becomes a change in ten places. The real world solved this problem long ago. A conductor says “play” to the whole orchestra, and each musician plays his own instrument in his own way. Polymorphism is the principle which allows the billing code to say “pay” without knowing which payment it is talking to. In the previous article, we discussed inheritance and its “is a” relationship. In this article, we are going to see what is polymorphism, first in the real world and in philosophy, and then the two ways it is achieved in object-oriented languages, subclass polymorphism and subtype polymorphism, and why a subclass is not always a subtype. Unlike the previous articles, this one has code, since the difference is best seen in code.

Object-Oriented Thinking series:

  1. How to model the real world with objects? - Part 1
  2. How do we organize what we know? - Part 2
  3. What is abstraction? - Part 3
  4. What is encapsulation? - Part 4
  5. What is inheritance? - Part 5
  6. What are subtype and subclass polymorphism? (this article)
  7. How objects relate to each other? - Part 7
  8. How all these concepts connect? - Part 8

TL; DR Summary

  • Polymorphism means “many forms”, the same request can be handled differently by different objects.
  • In the real world, polymorphism is multiple forms for one behaviour, many ways to express, implement and solve the same thing.
  • The one who asks needs to know only what to ask, each form knows how to do it.
  • The caller depends on what an object can do, not on what exact class it is.
  • Subclass polymorphism is achieved by class inheritance and method overriding, the child reuses the parent’s code and replaces some behaviour.
  • Subtype polymorphism is achieved when an object can be used wherever its type is expected, normally through an interface, and it keeps the promises of that type.
  • Liskov Substitution Principle - A subtype must be usable in place of its parent type without breaking the correctness of the program.
  • Every subclass is a subtype for the compiler, but not always for the behaviour. Square as a subclass of Rectangle is the classic example.
  • Program to an interface, not to an implementation.

Polymorphism in the real world and in philosophy

The word comes from Greek, “poly” means many and “morph” means form. Long before software, the word was used in science. Chemists call it polymorphism when the same substance exists in different crystal forms, and biologists call it polymorphism when the same species appears in clearly different forms. Let us discuss the different faces of polymorphism, without any computer.

Polymorphism is multiple forms of the same thing

Diamond and graphite are both pure carbon. One is the hardest natural material and is used in jewellery, the other is soft and is used in the pencil we write with. Same substance, very different forms. In the same way, water is ice in the freezer, liquid in the glass and steam over the cooking pot. What it is doesn’t change, only the form changes.

Polymorphism is one behaviour, many forms

The following diagram depicts an orchestra. The conductor gives one request, “play”. The violinist draws the bow, the flutist blows air, the drummer strikes the drum and the pianist presses the keys. The conductor doesn’t know how to play each instrument, and he doesn’t need to. He knows what to ask, each musician knows how to do it.

One request, many forms
One request, many forms

This is the heart of polymorphism, multiple forms for one behaviour. If the conductor had to give separate instructions to each musician, “move your bow like this, press this key now”, the orchestra could never play a symphony, and adding a new instrument would mean the conductor has to learn it first.

Polymorphism is multiple expressions of the same concept

When we greet someone, an Indian joins his palms and says namaste, an Englishman shakes hands, a Japanese bows. The meaning is the same, “I respect you and I am happy to meet you”, the expressions are different. Similarly, the number five can be written as “5”, “V” in Roman numerals, “five” in English, “ஐந்து” in Tamil or five tally marks. One concept, multiple representations, and none of them is more correct than the others.

Polymorphism is the same request to different things

We use the word “open” every day, open the door, open the bottle, open the book, open a bank account. The word is the same, but each thing does it in its own way, the door swings, the bottle cap twists, the book turns its cover and the bank creates an account. We don’t learn a different word for each one. The one who asks uses one simple word, and the thing which receives it decides what it means for itself.

Polymorphism is multiple ways to implement the same promise

A lock has one promise, “only the authorized person can open”. A key lock, a number lock and a fingerprint lock keep the same promise in completely different ways. A house owner who wants security doesn’t care which mechanism is inside, as long as the promise is kept. When a better lock comes, he can replace it without changing the door.

Polymorphism is multiple ways to solve the same problem

To travel from Chennai to Bengaluru, we can take a bus, a train, a car or a flight. The problem is the same, reach Bengaluru, the ways to solve it are different, each with its own cost, time and comfort. The traveller first decides the goal, then chooses the way, and the goal doesn’t change when the way changes. Tomorrow, if a new way of travel comes, the goal is still the same.

A standard is what makes many forms possible

The power socket in our house doesn’t know whether we are plugging a fan, a mobile charger or a mixer grinder. It just provides power through a standard plug, and each device does its own thing with it. The socket is the one who asks, the plug shape is the agreement and each device is a different form. Without the standard plug, every new device would need a new socket.

Notice that a fan and a mobile charger are not the same kind of thing at all, they have no common parent like the doctor and the surgeon. They only keep the same agreement. This is the family resemblance of Wittgenstein we discussed in Part 2, things can be treated the same way because they share a behaviour, not because they share a family. Keep this in mind, it is exactly the difference between subclass polymorphism and subtype polymorphism later in this article.

So, what is polymorphism in real life?

Based on the above, find below the faces of polymorphism we have seen,

  • Multiple forms - The same thing in different forms (carbon, water).
  • One behaviour, many forms - One request, each one does it in its own way (the orchestra).
  • Multiple expressions and representations - The same meaning, different ways to express it (greetings, the number five).
  • The same request to different things - One word, each thing decides what it means (open).
  • Multiple implementations - The same promise, kept in different ways (the locks).
  • Multiple ways to solve the same problem - The same goal, different approaches (the travel).
  • A shared agreement - Many forms are possible only because of a common standard (the plug).

All of them come down to one sentence, polymorphism is multiple forms for one behaviour. Now, let us move to object-oriented thinking and see how this is used to design software.

What is polymorphism in object-oriented thinking?

Polymorphism is the ability of different objects to respond to the same message, each in its own way, so that the code sending the message doesn’t need to know the exact kind of object it is talking to.

In simple terms, the billing code is the conductor, the payment objects are the musicians and “pay” is the request. The billing code knows what to ask, each payment knows how to do it.

Basically, there are few kinds of polymorphism in programming languages,

  • Ad hoc polymorphism - Same method name with different parameters, called as method overloading.
  • Parametric polymorphism - Same code working for any type, called as generics, like List<Item> and List<Customer>.
  • Inclusion polymorphism - An object of a specific type can be used wherever a more general type is expected. This is the one which is at the heart of object-oriented thinking, and it is achieved through subclasses and subtypes.

In this article, we will focus on the third one. Again, it comes in two flavours, which we already saw in the real world. Subclass polymorphism is like the doctor and the surgeon, the forms share a common parent and inherit from it. Subtype polymorphism is like the locks and the plug, the forms may share nothing except the promise they keep.

How it works behind the scenes?

When we call a method on an object through a general type, the actual method to execute is decided while the program is running, based on the real object, not based on the type of the variable. This is called as dynamic dispatch or late binding.

Payment payment = new CardPayment();
payment.complete(140);   // CardPayment's pay() runs, decided at runtime

The variable says Payment, the object is a CardPayment, so inside complete(), CardPayment’s pay() is executed. We will see the Payment classes in the next section. This single feature is what makes polymorphism possible.

Subclass polymorphism

Subclass polymorphism is the polymorphism achieved through class inheritance, where a child class extends a parent class, reuses its code and overrides some of its methods to provide its own behaviour.

The following diagram depicts subclass polymorphism with payments. The Payment base class has the common behaviour like completing the payment and printing the receipt, and each kind of payment overrides how the payment is actually done. CardPayment also refines the receipt to print the card slip. The checkout code only calls complete() on Payment, and at runtime the actual object decides which pay() runs.

Subclass polymorphism
Subclass polymorphism

Example:

public abstract class Payment {
    public void complete(double amount) {
        pay(amount);
        printReceipt(amount);
    }

    protected abstract void pay(double amount);

    protected void printReceipt(double amount) {
        System.out.println("Paid: " + amount);
    }
}

public class CashPayment extends Payment {
    protected void pay(double amount) {
        System.out.println("Collect cash and open the drawer");
    }
}

public class CardPayment extends Payment {
    protected void pay(double amount) {
        System.out.println("Send amount to card machine");
    }

    protected void printReceipt(double amount) {
        super.printReceipt(amount);
        System.out.println("Card slip printed");
    }
}

The billing code only knows Payment,

public void checkout(Bill bill, Payment payment) {
    payment.complete(bill.getTotal());
}

When the mobile wallet comes, we add WalletPayment extends Payment, and checkout() doesn’t change at all.

  • Pros - Common code is written once in the parent. Easy to add a new kind when the family is stable.
  • Cons - The child is tied to the parent’s code, all the problems of inheritance we discussed in the previous article, fragile base class and deep hierarchies, apply here. A class can extend only one parent in Java and C#.

Subtype polymorphism

Subtype polymorphism is the polymorphism achieved when an object of one type (the subtype) can be safely used wherever another type (the supertype) is expected, because it supports all the operations and keeps all the promises of the supertype.

The key word is “promises”. Subtyping is about behaviour, not about code reuse. In Java and C#, the cleanest way to express a subtype is an interface, it defines only the contract, what can be done and what is guaranteed, and has no code to inherit.

The following diagram depicts the subtype polymorphism with discount rules. The bill depends only on the DiscountRule interface, the link highlighted in purple, and doesn’t know which discount it is applying. The three discount rules share no code, they only implement the same contract and each one keeps its promise, the result is never negative and never more than the total.

Subtype polymorphism
Subtype polymorphism

Example:

/**
 * Promise: returns the total after discount,
 * never negative and never more than the given total.
 */
public interface DiscountRule {
    double apply(double total);
}

public class FestivalDiscount implements DiscountRule {
    public double apply(double total) {
        return total > 1000 ? total * 0.95 : total;
    }
}

public class LoyaltyDiscount implements DiscountRule {
    private final double points;

    public LoyaltyDiscount(double points) {
        this.points = points;
    }

    public double apply(double total) {
        return Math.max(0, total - points);
    }
}

public class NoDiscount implements DiscountRule {
    public double apply(double total) {
        return total;
    }
}

The bill uses any of them,

public double getPayableAmount(DiscountRule rule) {
    return rule.apply(getTotal());
}

FestivalDiscount, LoyaltyDiscount and NoDiscount share no code at all, but all of them are DiscountRule, because all of them keep the promise, the result is never negative and never more than the total. Notice that LoyaltyDiscount uses Math.max, otherwise a customer with 200 points and a bill of 150 would get a negative amount, and the promise is broken.

Info: We used double to keep the examples short. As we discussed in Thinking Like a Programmer - Part 3, use BigDecimal (Java) or decimal (C#) for real money.

Liskov Substitution Principle

Barbara Liskov described this idea in her 1987 keynote “Data Abstraction and Hierarchy”, and later formalized it with Jeannette Wing in 1994. It is called as Liskov Substitution Principle (LSP), the “L” in the SOLID principles.

In simple terms, if a piece of code works correctly with the parent type, it must also work correctly with any of its subtypes, without knowing about them. A subtype,

  • Must accept at least everything the parent accepts (it should not demand more).
  • Must give at least everything the parent guarantees (it should not promise less).
  • Must not break the invariants of the parent.
  • Must not throw surprises, like an error for an operation the parent supports.

Why a subclass is not always a subtype?

Based on the above, you may be wondering, if CardPayment extends Payment, isn’t it automatically a subtype? For the compiler, yes. The compiler only checks the method names and parameter types, it cannot check the behaviour. For the correctness of the program, it is a subtype only if it keeps the parent’s promises. William Cook and his colleagues wrote a paper in 1990 with a clear title for this, “Inheritance Is Not Subtyping”.

The classic example is the rectangle and the square. In maths, a square is a rectangle, so it looks like a perfect “is a”,

public class Rectangle {
    protected int width, height;

    public void setWidth(int w)  { width = w; }
    public void setHeight(int h) { height = h; }
    public int area() { return width * height; }
}

public class Square extends Rectangle {
    public void setWidth(int w)  { width = w; height = w; }
    public void setHeight(int h) { width = h; height = h; }
}

The Rectangle promises, “setWidth changes only the width”. Now look at this code, which is correct for any rectangle,

public void resize(Rectangle r) {
    r.setWidth(5);
    r.setHeight(4);
    // expected: 20
    System.out.println(r.area());
}

Pass a Rectangle, it prints 20. Pass a Square, it prints 16. The compiler is happy, Square is a subclass of Rectangle, but the program is wrong. Square reused Rectangle’s code, but it broke its promise, so it is a subclass, not a subtype.

The following diagram depicts the difference. On the left, Square is a subclass of Rectangle and is not a safe substitute, the same resize() code gives 20 for a rectangle and 16 for a square. On the right, both Rectangle and Square implement a Shape type whose only promise is area(), and both keep it. There is no setWidth() in Shape, so there is no promise for Square to break.

Subclass vs subtype
Subclass vs subtype
public interface Shape {
    int area();
}

public class Rectangle implements Shape {
    private final int width, height;
    public Rectangle(int width, int height) { this.width = width; this.height = height; }
    public int area() { return width * height; }
}

public class Square implements Shape {
    private final int side;
    public Square(int side) { this.side = side; }
    public int area() { return side * side; }
}

Keep in mind that the model “a square is a rectangle” is true in maths, but in our software, a rectangle has a promise about changing width and height independently, and a square cannot keep it. Again, what is essential depends on the behaviour we promise, not on the name, the same abstraction thinking we discussed in Part 3. The square is the penguin of software, which we met in the previous article, a true member of the family by name, which cannot keep one of the family’s promises.

Subclass vs Subtype polymorphism

Find below the quick comparison,

Subclass polymorphismSubtype polymorphism
Based onClass inheritance (extends)Type contract (interface, or a class used only as contract)
Main purposeReuse the parent’s code and override some behaviourSubstitute safely wherever the type is expected
SharesCode and stateOnly the contract (promises)
Checked by compilerMethod signaturesMethod signatures, but behaviour is our responsibility
Coupling− Tight, child depends on parent’s internals+ Loose, depends only on the contract
Multiple− One parent class in Java and C#+ A class can implement many interfaces
Risk− Subclass may break parent’s promises+ Lower, if the contract is clearly written

Most importantly, these two are not enemies. A good subclass is also a good subtype, CardPayment keeps all the promises of Payment, so it is both. The problem is only when we use subclassing for code reuse and forget about the promises.

Guidelines

  • Program to an interface, not to an implementation. This is another famous guideline from the Gang of Four book. The billing code should depend on Payment and DiscountRule, not on CardPayment and FestivalDiscount.
  • Write the promises of every type, in the comments or the documentation, what it accepts, what it guarantees and what it never does.
  • Use the substitution test, before creating a subclass, ask “will every code which works with the parent still work with this child?”. If not, it is not a subtype, don’t extend.
  • Prefer interfaces for variation points like payments, discounts and taxes, where new kinds keep coming.
  • Use subclass polymorphism when there is a real common behaviour to reuse and the family is stable, like the receipt printing in Payment.
  • Don’t check the type with “if (payment instanceof CardPayment)”, otherwise the polymorphism is lost and every new type needs a change in that place.

Wrap up

In this article, we have looked at polymorphism in the real world and in philosophy, as multiple forms, expressions, implementations and ways to solve the same problem, and then in object-oriented thinking, dynamic dispatch, subclass polymorphism, subtype polymorphism, the Liskov Substitution Principle and why a subclass is not always a subtype. I really appreciate that you took the time to read this article and I hope this article provided you some insights into polymorphism beyond the syntax. So far, we have looked at the principles one object or one family at a time. In the next article, I will walk you through how objects relate to each other, association, aggregation, composition and dependency, and how the “is a part of” hierarchy from Part 2 comes back.

Related Posts