Polymorphism in Java (Method Overloading + Method Overriding)
Polymorphism in Java: Overloading and Overriding (With Examples)
✨ Quick Summary
In this post, you’ll learn what Polymorphism is in Java and how it works in OOP. We will cover Method Overloading (Compile-time Polymorphism) and Method Overriding (Run-time Polymorphism) with simple examples.
In our previous post, we learned about Inheritance and how one class can acquire properties of another class.
Now let’s learn another powerful OOP concept: Polymorphism.
1) What is Polymorphism?
The word Polymorphism means: many forms.
In Java, polymorphism means:
- ✅ One method can behave differently in different situations
- ✅ One object can take multiple forms
2) Types of Polymorphism in Java
Java has 2 main types of polymorphism:
- Compile-time Polymorphism (Method Overloading)
- Run-time Polymorphism (Method Overriding)
3) Method Overloading (Compile-time Polymorphism)
Method overloading means: same method name but different parameters.
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 OverloadingExample {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(10, 20));
System.out.println(c.add(10, 20, 30));
}
}
4) Method Overriding (Run-time Polymorphism)
Method overriding means: child class provides a new version of a method from the parent class.
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 OverridingExample {
public static void main(String[] args) {
Animal a1 = new Dog();
Animal a2 = new Cat();
a1.sound(); // Dog barks
a2.sound(); // Cat meows
}
}
5) Why Polymorphism is Useful?
Polymorphism helps in:
- ✅ Writing flexible code
- ✅ Reusing code easily
- ✅ Creating real-world applications
Conclusion
Polymorphism is a key concept of Java OOP. Once you understand this, you are very close to mastering OOP in Java.
In the next post, we will learn about Abstraction in Java with examples!
Great.
ReplyDelete