Understanding OOP Concepts: Polymorphism

Published on February 22, 2020 45 sec read

HIRE US 🖐
We're available to do freelance project. Take a look at our services!

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();
    }
}

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *