What is Method Overloading and Method Overriding in Java?
Method Overloading and Method Overriding are two core concepts of Polymorphism in Java. The key difference is that overloading occurs at compile-time (static polymorphism), while overriding occurs at runtime (dynamic polymorphism).
1. Method Overloading (Compile-Time Polymorphism)
Multiple methods in the same class share the same name but have different parameters (number, type, or order).
class Calculator {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 10)); // Output: 15
System.out.println(calc.add(5, 10, 15)); // Output: 30
System.out.println(calc.add(5.5, 2.5)); // Output: 8.0
}
}
2. Method Overriding (Runtime Polymorphism)
A child class provides a specific implementation of a method already defined in its parent class.
class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound(); // Output: Dog barks
}
}
Key Differences
| Feature | Overloading | Overriding |
|---|---|---|
| Polymorphism Type | Compile-time | Runtime |
| Occurs In | Same class | Parent-Child classes |
| Return Type | Can be different | Must be same |
Master these concepts with Online Learner for your Java interviews!
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
