Method Overloading and Method Overriding
Method Overloading and Method Overriding
1. Method Overloading
Method overloading occurs when two or more methods in the same class have the same name but differ in
their parameter lists (different number of parameters, different types of parameters, or both). It is a form of
compile-time polymorphism.
Example of Method Overloading:
java
Copy code
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
2. Method Overriding
Method overriding occurs when a subclass provides a specific implementation for a method that is already
defined in its parent class. It is a form of runtime polymorphism. The method in the subclass should have
the same name, return type, and parameters as in the parent class.
Example of Method Overriding:
java
Copy code
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
// Overriding the sound method
void sound() {
System.out.println("Dog barks");
}
public static void main(String[] args) {
Animal animal = new Animal();
Dog dog = new Dog();
animal.sound(); // Calls the parent class method
dog.sound(); // Calls the overridden method in Dog
}
}
Output:
Animal makes a sound
Dog barks