Java Polymorphism

Polymorphism is one of the core principles of Object-Oriented Programming (OOP) in Java. It allows one entity (like a method or object) to take multiple forms. The term polymorphism comes from the Greek words "poly" (many) and "morph" (forms), meaning the ability to process objects differently based on their data type or class.

Types of Polymorphism in Java

Compile-Time Polymorphism (also called Static Polymorphism)

  • Achieved through method overloading.
  • The method to be called is resolved at compile time.
Example
class Calculator {
// Overloaded methods
int add(int a, int b) {
return a + b;
}

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

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

public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Addition of 2 integers: " + calc.add(10, 20)); // Calls the first method
System.out.println("Addition of 2 doubles: " + calc.add(10.5, 20.5)); // Calls the second method
System.out.println("Addition of 3 integers: " + calc.add(10, 20, 30)); // Calls the third method
}
}

Try it yourself


Runtime Polymorphism (also called Dynamic Polymorphism)

  • Achieved through method overriding.
  • The method to be called is determined at runtime based on the actual object
Example
class Animal {
void sound() {
System.out.println("Animals make sounds.");
}
}

class Cat extends Animal {
void sound() {
System.out.println("Cat meows.");
}
}

public class Main {
public static void main(String[] args) {
Animal animal;

animal = new Cat(); // Cat object is assigned to an Animal reference
animal.sound(); // Calls Cat's overridden method
}
}

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.