Understanding OOP Concepts: Polymorphism

Today we’re going to learn about Polymorphism. Let’s get started:

Table of Contents

  1. What is Polymorphism
  2. Compile-time Polymorphism
  3. Runtime Polymorphism

What is Polymorphism

It means ‘many forms‘. Polymorphism is derived from two Greek words poly and morphs. So polymorphism means having many forms. It is useful for code reusability.

There are two types of Polymorphism:

  • Compile-time Polymorphism
  • Runtime Polymorphism

Compile-time Polymorphism

Compile-time polymorphism is also known as static polymorphism. This type is achieved by method overloading or operator overloading. Lets’ see an example:

class ParentClass {
    public int sum(int a, int b) { // pass 2 parameter
        return a + b;
    }

    public int sum(int a, int b, int c) { // pass 3 parameter
        return a * b;
    }
}

class TestMethodOverloading extends ParentClass {
    public static void main(String[] args) {
        ParentClass parentClass = new ParentClass();

        int result1 = parentClass.sum(2, 4); // first method
        int result2 = parentClass.sum(2, 4, 6); /// 2nd method

        System.out.println(result1);
        System.out.println(result2);
    }
}

Runtime Polymorphism

Runtime polymorphism is also known as Dynamic Method Dispatch. This type is achieved by method overriding. Lets’ see an example:

class ParentClass {
    void displayInfo() {
        System.out.println("This is the parent class");
    }
}

class SubClass extends ParentClass {
    void displayInfo() {
        System.out.println("This is the subclass");
    }
}

class TestMethodOverriding extends ParentClass {
    public static void main(String[] args) {

        ParentClass parentClass;

        parentClass = new ParentClass();
        parentClass.displayInfo();

        parentClass = new SubClass();
        parentClass.displayInfo();
    }
}

Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.