what is polymorphism in java

Read the full article about polymorphism and runtime polymorphism in Java

Polymorphism is one of the four essential principles of object-oriented programming (OOP) that Java supports. It enables the treatment of objects of distinct classes as objects of a common interface or superclass. Polymorphism in Java is classified into two types: compile-time polymorphism (also known as method overloading) and runtime polymorphism (also known as method overriding).

Compile-time Polymorphism (Method Overloading):

class Calculator {

int add(int a, int b) {

return a + b;

}

double add(double a, double b) {

return a + b;

}

}

public class Main {

public static void main(String[] args) {

Calculator calculator = new Calculator();

System.out.println(calculator.add(1, 2)); // Invokes the first method

System.out.println(calculator.add(1.5, 2.5)); // Invokes the second method

}

}

Method overloading is a feature that allows a class to have many methods with the same name as long as their parameter lists differ (in terms of the amount or type of parameters).

Runtime Polymorphism (Method Overriding):

Method overloading is a feature that allows a class to have many methods with the same name as long as their parameter lists differ (in terms of the amount or type of parameters).

class Animal {

void sound() {

System.out.println("Animal makes a sound");

}

}

class Dog extends Animal {

void sound() {

System.out.println("Dog barks");

}

}

public class Main {

public static void main(String[] args) {

Animal animal = new Dog(); // Using polymorphism

animal.sound(); // Invokes the overridden method in Dog class

}

}

In this example, even though the reference variable animal is of type Animal, it refers to an instance of Dog. During runtime, the sound() method of the Dog class is invoked.

Polymorphism is an important notion in object-oriented programming because it provides for code flexibility and expansion. By programming to interfaces or basic classes rather than specific implementations, you can develop more generic and reusable code.