Polymorphism in Java: Definition, Types, and Examples

Polymorphism in Java

Polymorphism is an object-oriented programming concept in which a single reference variable can exhibit different behaviors depending on the object it refers to.

Types of Polymorphism

Polymorphism in Java is classified into two types:
  1. Compile-Time Polymorphism
  2. Run-Time Polymorphism

1. Compile-Time Polymorphism

In compile-time polymorphism, the method resolution is performed by the compiler.

Key Points

  • The compiler resolves the method call based on the parameter list.
  • Once method resolution is done, the compiler performs static binding.
  • In static binding:
              ✓ The method declaration is bound to the method definition at compile time.
  • Compile-time polymorphism is achieved using method overloading.

Example

class Calculator {
    int add(int a, int b) {
        return a + b;
    }

    double add(double a, double b) {
        return a + b;
    }
}

2. Run-Time Polymorphism

In run-time polymorphism, the method resolution is performed by the JVM.

Key Points

  • The JVM resolves the method call based on the object present inside the reference variable.
  • Once method resolution is done, the JVM performs dynamic binding.
  • In dynamic binding:
            ✓ The method declaration is bound to the method definition at runtime.
  • Run-time polymorphism is achieved using method overriding.

Example

class Parent {
    void show() {
        System.out.println("Parent class method");
    }
}

class Child extends Parent {
    void show() {
        System.out.println("Child class method");
    }
}

Parent p = new Child();
p.show(); // Output: Child class method

Requirements for Run-Time Polymorphism

To achieve run-time polymorphism, the following conditions must be satisfied:
  • Inheritance
  • Method Overriding
  • Up Casting

Comments

Popular posts from this blog

History of Java Programming Language | Features, Origin & Uses

Inheritance in Java: Types, Examples, and Explanation

Java Programming Features Every Beginner Should Know