Method overloading and method overriding are two types of Java polymorphism, but they are fundamentally different.
Method overloading is a type of compile-time (or static) polymorphism where multiple methods with the same name but different parameters are defined in a class. Each overloaded method can have a different number, order, or type of parameters. When a method is called, the Java compiler determines which method to execute based on the number and types of arguments passed to the method.
Here's an example of method overloading:
class MathUtils {
public int add(int x, int y) {
return x + y;
}
public double add(double x, double y) {
return x + y;
}
}
In this example, the MathUtils class has two methods named add(), but they take different parameter types (integers and doubles). When the add() method is called, the Java compiler determines which version of the method to execute based on the types of the arguments passed to the method.
Method overriding, on the other hand, is a type of runtime (or dynamic) polymorphism where a subclass provides a different implementation of a method that is already defined in its superclass. The method in the subclass must have the same name, return type, and parameters as the method in the superclass. When the method is called on an object of the subclass, the implementation in the subclass is executed instead of the implementation in the superclass.
Here's an example of method overriding:
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("The dog barks");
}
}
In this example, the Animal class has a makeSound() method that prints "The animal makes a sound" to the console. The Dog class extends Animal and overrides the makeSound() method with its own implementation that prints "The dog barks" to the console. When the makeSound() method is called on a Dog object, the implementation in the Dog class is executed instead of the implementation in the Animal class.
In summary, method overloading is when multiple methods with the same name but different parameters are defined in a class, while method overriding is when a subclass provides a different implementation of a method that is already defined in its superclass.