In Java, method overriding and method overloading are two fundamental concepts in object-oriented programming that allow developers to define methods with the same name but different behaviors. Here's a detailed look at the rules and characteristics of each:
Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The overriding method in the subclass must have the same name, return type, and parameter list as the method in the superclass.
protected
, the overriding method cannot be private
.@Override
annotation to indicate that a method is intended to override a method in the superclass. This helps to catch errors at compile-time.class SuperClass {
void display() {
System.out.println("Display method in SuperClass");
}
}
class SubClass extends SuperClass {
@Override
void display() {
System.out.println("Display method in SubClass");
}
}
public class Test {
public static void main(String[] args) {
SuperClass obj = new SubClass();
obj.display(); // Calls the display method in SubClass
}
}
Method overloading occurs when multiple methods in the same class have the same name but different parameter lists. Overloaded methods can have different return types and access modifiers.
class Example {
void display() {
System.out.println("Display method with no parameters");
}
void display(int a) {
System.out.println("Display method with one integer parameter: " + a);
}
void display(String s) {
System.out.println("Display method with one string parameter: " + s);
}
}
public class Test {
public static void main(String[] args) {
Example obj = new Example();
obj.display(); // Calls display method with no parameters
obj.display(10); // Calls display method with one integer parameter
obj.display("Hello"); // Calls display method with one string parameter
}
}
Overriding:
Overloading:
Understanding these concepts and their rules is crucial for writing effective and maintainable Java code, leveraging polymorphism, and ensuring clear method interfaces.