Today I learned what is polymorphism in java .Polymorphism in Java is one of the core concepts in object-oriented programming (OOPS) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms.
Types of Polymorphism in Java
1.Compile-Time Polymorphism (Method Overloading)
*Achieved using method overloading (same method name, different parameters).
*Decided by the compiler.
Exam program
class Calculator {
int add(int a, int 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 c = new Calculator();
System.out.println("Sum of 2 numbers: " + c.add(10, 20));
System.out.println("Sum of 3 numbers: " + c.add(10, 20, 30));
}
}
**Output**
Sum of 2 numbers: 30
Sum of 3 numbers: 60
2.Runtime Polymorphism (Method Overriding)
*Achieved using method overriding (subclass provides its own implementation of a method already defined in parent class).
*Decided at runtime using dynamic method dispatch.
Example program
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal a;
a = new Dog();
a.sound();
a = new Cat();
a.sound();
}
}
**Output**
Dog barks
Cat meows
Top comments (0)