Overriding vs. Overloading Polymorphism

Polymorphism is one of the key concepts of Object-Oriented Programming (OOP), alongside encapsulation and inheritance.

The word polymorphism comes from the Greek words poly (many) and morph (forms). In programming, polymorphism refers to the ability of methods or objects to take different forms or behave differently depending on the context in which they are used.

There are two important types of polymorphism that we will explore in this tutorial:

  • Overriding polymorphism: When a subclass provides its own implementation of a method already defined in its parent class.
  • Overloading polymorphism: When multiple methods share the same name but accept different numbers or types of parameters.
Overriding PolymorphismOverloading Polymorphism

Part 1: Overriding Polymorphism

Let’s create a simple object-oriented program to calculate the perimeter and area of different geometric shapes, including circles, squares and rectangles. Our program will be based on the following class diagram:

This class diagram highlights the use of inheritance between a parent class called Shape and three subclasses called Circle, Square and Rectangle.

Our parent class, Shape, defines two methods:

  • getPerimeter() – Returns the perimeter of a shape.
  • getArea() – Returns the area of a shape.

All three shapes have something in common: they have a perimeter and an area. However, the mathematical formulas used to calculate these values differ depending on the type of shape. The parent class cannot provide a single mathematical formula that works for every shape.

Instead, each subclass will override these two methods to provide its own implementation.

Step 1: Implementing the parent class

Let’s start by creating our Shape class.

class Shape:
    def getPerimeter(self):
        pass

    def getArea(self):
        pass

Notice that both methods contain the Python keyword pass.

This keyword acts as a placeholder. It allows us to define a method without providing any instructions for it to execute.

Our Shape class is intended to act as a base class for other shapes. In this example, it behaves like an abstract class: objects will not be instantiated directly from this abstract class. Circle, square and rectangle objects will instead be instantiated from the corresponding sub-classes.

Step 2: Implementing the Circle subclass

We can now create our first subclass, Circle.

A circle has one important property: its radius.

The formulas for calculating its perimeter (circumference) and area are:
\text{Perimeter} = 2\pi r \text{Area} = \pi r^2 We can implement these formulas in Python as follows:

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def getPerimeter(self):
        return 2 * 3.14 * self.radius

    def getArea(self):
        return 3.14 * self.radius ** 2

Notice that the Circle class inherits from Shape, as indicated by class Circle(Shape):.

More importantly, the Circle class defines its own versions of getPerimeter() and getArea().

These methods have exactly the same names as those in the parent class, but they contain specific instructions for calculating the perimeter and area of a circle.

This is an example of method overriding.

Step 3: Implementing the Square subclass

Next, we can create a Square class.

A square has four sides of equal length.

The formulas are:
\text{Perimeter} = 4 \times width \text{Area} = width^2

class Square(Shape):
    def __init__(self, width):
        self.width = width

    def getPerimeter(self):
        return 4 * self.width

    def getArea(self):
        return self.width ** 2

Once again, we are overriding the two methods inherited from the Shape class.

Although the method names remain identical, their implementations are different from those in the Circle class.

Step 4: Implementing the Rectangle subclass

Finally, let’s implement our Rectangle class.

A rectangle has two properties: its width and its height.
\text{Perimeter} = 2 \times width + 2 \times height \text{Area} = width \times height

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def getPerimeter(self):
        return 2 * (self.width + self.height)

    def getArea(self):
        return self.width * self.height

Our three subclasses now provide their own implementations of the same two methods.

Step 5: Using our classes


Let’s instantiate a few objects using our classes.

For example, we can represent a CD, a vinyl record and a square vinyl record cover using the following Python code:

Now, scroll up to the top of this page to access the second tab to find out more about overloading polymorphism!

Part 2: Overloading Polymorphism

Now that we understand overriding polymorphism, let’s explore another concept: method overloading.

Overloading polymorphism allows a class to define several methods with the same name but different parameter lists.

Depending on the number or types of arguments provided when calling the method, a different implementation is executed.

This feature is available in languages such as Java and C++, but Python does not support traditional method overloading in the same way.

Let’s investigate this limitation using our Shape class.

Step 1: Adding a colour property

We will extend our Shape class by adding a new property called colour.

This property will store a hexadecimal colour code, such as:

  • #FF0000 – Red
  • #00FF00 – Green
  • #0000FF – Blue
  • #FFFF00 – Yellow
  • #000000 – Black

We will initially set the colour of every shape to black: #000000.

class Shape:
    def __init__(self):
        self.colour = "#000000"

    def getPerimeter(self):
        pass

    def getArea(self):
        pass

Since all our shapes inherit from the Shape class, they can also inherit the colour property.

However, we must ensure that the constructors of our subclasses call the parent constructor using super().__init__().

For instance, our Circle class constructor becomes:

class Circle(Shape):
    def __init__(self, radius):
        super().__init__()
        self.radius = radius

We would make a similar change to the constructors of Square and Rectangle, while keeping their existing perimeter and area methods.

Step 2: Creating a setColour() method

We would like to give the programmer two different ways to set the colour of a shape.

Option 1: Using a hexadecimal colour code

The programmer could supply a hexadecimal string directly:

cd.setColour("#FF0000")

To achieve this, we could implement the following method in our parent Shape class:

def setColour(self, hexaCode):
    self.colour = hexaCode

Option 2: Using three RGB values

Alternatively, the programmer could provide three integer values representing the red, green and blue components of the colour.

For example:

cd.setColour(255, 0, 0)

This method would need to convert the three RGB values into a hexadecimal colour code before storing the result in the colour property.

def setColour(self, red, green, blue):
    hexaCode = f"#{red:02X}{green:02X}{blue:02X}"
    self.colour = hexaCode
Step 3: Attempting to overload setColour()

In a programming language that supports traditional method overloading, we could define both versions of setColour() inside our Shape class.

Our intended implementation would look like this:

class Shape:
    def __init__(self):
        self.colour = "#000000"

    # Version 1: Using a hexadecimal code
    def setColour(self, hexaCode):
        self.colour = hexaCode

    # Version 2: Using three RGB values
    def setColour(self, red, green, blue):
        self.colour = f"#{red:02X}{green:02X}{blue:02X}"

    def getPerimeter(self):
        pass

    def getArea(self):
        pass

Our intention is that Python should automatically select the correct version based on the arguments provided.

For instance:

cd = Circle(6)
cd.setColour("#FF0000")  # Version 1
cd.setColour(255, 0, 0)  # Version 2

Unfortunately, this will not work as intended in Python!

Why doesn’t method overloading work in Python?

Unlike Java or C++, Python does not support traditional method overloading by defining multiple methods with the same name but different parameter lists.

When Python encounters two method definitions with the same name inside a class, the second definition replaces the first.

This demonstrates an important difference between overriding and overloading polymorphism.

Python fully supports method overriding through inheritance, but it does not method overloading.

Step 4: An alternative approach in Python

One straightforward solution is to give our two methods different names.

For example, we could use:

  • setColourHexa(hexaCode) to set the colour using a hexadecimal string.
  • setColourRGB(red, green, blue) to set the colour using three integer values.

Our revised Shape class would become:

class Shape:
    def __init__(self):
        self.colour = "#000000"

    def setColourHexa(self, hexaCode):
        self.colour = hexaCode

    def setColourRGB(self, red, green, blue):
        self.colour = f"#{red:02X}{green:02X}{blue:02X}"

    def getPerimeter(self):
        pass

    def getArea(self):
        pass

We can now use both methods without generating any errors.

# Create a circle
cd = Circle(6)
# Set its colour using a hexadecimal code
cd.setColourHexa("#FF0000")
print(cd.colour)
# Set its colour using RGB values
cd.setColourRGB(0, 255, 0)
print(cd.colour)

Output:

#FF0000
#00FF00

Python Code

This approach is simple and makes it clear to the programmer which format should be used when setting the colour of a shape.

However, it is important to understand that using different method names is not method overloading. It is simply an alternative way of providing similar functionality.

Summary: Overriding vs. Overloading Polymorphism

Let’s compare the two concepts.

Overriding Overloading
Definition A subclass replaces a method inherited from its parent class Multiple methods share the same name but have different parameter lists
Inheritance required? Yes No
Method name Same Same
Parameters Normally the same Different number or types
Purpose Provide class-specific behaviour Provide different ways to perform a similar operation
Python support Fully supported Not directly supported through multiple same-named definitions

In our example, overriding polymorphism allowed Circle, Square and Rectangle to implement their own versions of getPerimeter() and getArea().

Overloading polymorphism would have allowed us to define two versions of setColour(), one accepting a hexadecimal string and the other accepting three RGB values.

Although Python does not support traditional method overloading, we can achieve similar functionality using alternative techniques.

Did you like this challenge?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 4

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!