0% found this document useful (0 votes)
4 views1 page

Polymorphism Java Examples

Polymorphism in Java allows one interface to be used for different data types or actions, categorized into compile-time (method overloading) and runtime (method overriding). Examples include a Calculator class demonstrating method overloading and an Animal class with a Dog subclass showcasing method overriding. This concept enhances flexibility and reusability in code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views1 page

Polymorphism Java Examples

Polymorphism in Java allows one interface to be used for different data types or actions, categorized into compile-time (method overloading) and runtime (method overriding). Examples include a Calculator class demonstrating method overloading and an Animal class with a Dog subclass showcasing method overriding. This concept enhances flexibility and reusability in code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Polymorphism in Java with Examples

Polymorphism means 'many forms'. It allows one interface to be used for different data types or
actions.

Types of Polymorphism in Java:


1. Compile-time Polymorphism (Method Overloading)
2. Runtime Polymorphism (Method Overriding)

1. 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 static void main(String[] args) {


Calculator c = new Calculator();
System.out.println(c.add(2, 3)); // 5
System.out.println(c.add(2.5, 3.5)); // 6.0
}
}

2. Runtime Polymorphism (Method Overriding)

class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Dog barks");
}

public static void main(String[] args) {


Animal a = new Dog(); // Parent class reference to child object
a.sound(); // Output: Dog barks
}
}

You might also like