I have a confession: I’ve always been a bit rusty with the four basic rules of object oriented programming. These being abstraction, encapsulation, inheritance and today’s victim topic, polymorphism. I’m happy to say I now have a better understanding of this subject and hopefully I’ll be able to help you out too!
Let’s get that big word that my spell correct seems to think is wrong to be less scary. Polymorphism basically means “many forms” and it occurs almost directly as a result of inheritance. As a recap or general introduction, inheritance is an aspect that allows subclasses to inherit methods/attributes of classes.
Polymorphism in turn allows us to perform a single action in different ways by using these inherited methods. Let’s look at a quick example!
To begin with, we create a class and a few subclasses which inherit a method from their parent class. Here we have a House class with a door. All houses have doors, but not necessarily the same kind of door, so each of the subclasses have a different response for the door method.
class House {
public void houseDoor() {
System.out.println("The house has a door");
}
}
//TownHouse inherits methods/attributes from House
class TownHouse extends House {
public void houseDoor() {
//Different for each type of house, despite being the same method
System.out.println("The town house has a sliding glass door");
}
}
class FarmHouse extends House {
public void houseDoor() {
System.out.println("The farmhouse has a dutch door");
}
}
class SafeHouse extends House {
public void houseDoor() {
System.out.println("The safe house has a concrete door");
}
}
If I wanted to call on these classes, I need to create a new instance of each of these classes. This code simply prints the following output to the command-line, representing the different kinds of doors for each type of house.
class MainClass {
public static void main(String[] args) {
//Create a new instance of each of my classes
House myHouse = new House();
House myTownHouse = new TownHouse();
House myFarmHouse = new FarmHouse();
House mySafeHouse = new SafeHouse();
//Call on the method houseDoor from each of these new instances
myHouse.houseDoor();
myTownHouse.houseDoor();
myFarmHouse.houseDoor();
mySafeHouse.houseDoor();
}
}

For the full code that was featured in this blog, you can visit my git at: https://github.com/salkiduckyJUMP/RLHull-Repo/blob/master/Polymorphism.java
Bonus fact: this blog actually has an example of only one kind of polymorphism in Java! The houseDoor code above is method overriding, but you can also have method overloading. I won’t go into detail, but you can visit this link to learn more on the differences between this and the other type of polymorphism; https://www.geeksforgeeks.org/polymorphism-in-java/.
One thought on “Polymorphism in Java”