Java: Polymorphism

Introduction

Polymorphism refers to an objects ability to take on different forms. In Java, it is a simple, yet fundamental concept of objected oriented programming. In order to understand polymorphism, it is important to have a solid grasp of inheritance and interfaces in Java.

What is polymorphism?

A class is considered to be polymorphic if it passes more than one “is-a” test. An “is-a” test is a simple way of identifying the type a class belongs to; if the class belongs to more than one type then it is considered to be polymorphic. Consider this example:

The class Manager inherits from the Employee class and as all classes in Java, it also inherits from the Object class. Therefore:

A Manager is-a Manager

A Manager is-a Employee

A Manager is-a Object

Since the Manager class passes more than one “is-a” test it is polymorphic.

Note: All classes in Java are inherently polymorphic; an object of any class always passes at least two “is-a” tests, since it has it’s own type and the type Object (all classes inherit from the Object class in Java).

Usages

You may be wondering when we would need to use polymorphism. Let’s consider a scenario; your company is doing exceptionally well and you decided to give a $5000 bonus to every employee. A simple program that programmatically describes that scenario is given below:

Since our Manager, Receptionist, Designer and Developers classes all inherit from the Employee class; if can declare our listOfEmployees to be of the Employee type, any instance whose type inherits from the Employee class can be added to the listOfEmployees.

Therefore, polymorphism can be achieved via inheritance; we can use the parent class type(Employee in this case) as a reference variable for any instances of the child class. It can also be achieved via the use of interfaces.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store