Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.
In Java, method overloading and method overriding are two important concepts related to methods in classes.
- Method Overloading:
- Definition: Method overloading is a feature that allows a class to have more than one method having the same name, if their parameter lists are different.
- Criteria for Overloading:
- The method name must be the same.
- The parameter list must be different (either in the number of parameters or their types).
- Return types may or may not be the same.
Example of method overloading:
javaclass Example {
void display(int a) {
System.out.println("Displaying integer: " + a);
}void display(String b) {
System.out.println("Displaying string: " + b);
}
}
- Method Overriding:
- Definition: Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The overridden method in the subclass should have the same name, return type, and parameters as the method in the superclass.
- Criteria for Overriding:
- The method in the subclass must have the same signature (name, return type, and parameters) as the method in the superclass.
- The access level of the overriding method in the subclass cannot be more restrictive than the overridden method in the superclass.
- The overriding method can’t throw broader checked exceptions than the overridden method.
Example of method overriding:
javaclass Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}class Dog extends Animal {
void makeSound() {
System.out.println("Dog barks");
}
}
In summary, method overloading involves having multiple methods in the same class with the same name but different parameter lists, while method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass.