Overloading occurs when two or more methods in one class have the same method name but different parameters.
Overriding occurs when two methods have the same method name and parameters. One of the methods is in the parent class, and the other is in the child class. Overriding allows a child class to provide the specific implementation of a method that is already present in its parent class.
The two examples below illustrate their differences:
The table below highlights their key differences:
Must have at least two methods by the same name in the class.
Must have a different number of parameters.
If the number of parameters is the same, then it must have different types of parameters.
Overloading is known as compile-time polymorphism.
Must have at least one method by the same name in both parent and child classes.
Must have the same number of parameters.
Must have the same parameter types.
Overriding is known as runtime polymorphism.
Take a look at the code below:
class Dog{public void bark(){System.out.println("woof ");}}class Hound extends Dog{public void sniff(){System.out.println("sniff ");}public void bark(){System.out.println("bowl");}}class OverridingTest{public static void main(String [] args){Dog dog = new Hound();dog.bark();}}
In this overriding example, the dog
variable is declared to be a Dog
. During compile-time, the compiler checks if the Dog
class has the bark()
method. As long as the Dog
class has the bark()
method, the code compiles. At run-time, a Hound
is created and assigned to dog
, so, it calls the bark()
method of Hound
.
Take a look at the code below:
class Dog{public void bark(){System.out.println("woof ");}//overloading methodpublic void bark(int num){for(int i=0; i<num; i++)System.out.println("woof ");}}
In this overloading example, the two bark
methods can be invoked using different parameters. The compiler knows that they are different because they have different method signatures (method name and method parameter list).