Method Overloading Vs Method Overriding

Method Overloading:

A feature that allows a class to have two or more methods having same name but different argument is said to be Method Overloading. Two methods are said to be overloaded if and only if both methods having the same name but different argument types.
Also known as Static Binding, Compile-Time Polymorphism and Early Binding.
class Calculate {
public void area(int a) {//circle
System.out.println("Area of Circle = " + (3.14 * a * a));
}
public void area(int l, int b) { //rectangle
System.out.println("Area of Rectangle= " + (l * b));
}
}
In above example, we have created two overloaded methods, first area() method prints area of circle and second area() method prints area of rectangle.


Method Overriding:

The methods declared in parent class are by default available in the child class through the inheritance. But sometimes child may not be fully satisfied with the parent class method implementation, then the child is allow to redefine it based on its requirement, this process is known as Method Overriding.
Also known as Dynamic Binding, Run-Time Polymorphism and Late Binding.
class Bank {
public void printAddress() { // overridden method
System.out.println("Address of Bank.");
}
}
class SBI extends Bank {
@Override
public void printAddress() { // overriding method
System.out.println("Address of SBI.");
}
}
In above example, we have defined the printAddress() method in the subclass as defined in the parent class but it has some specific implementation.

Difference Between Method Overloading and Method Overriding:

1) Method Names:
Method Overloading:Must be same.
Method Overriding:Must be same.
2) Argument Types:
Method Overloading:Must be different or ordering of the arguments should be different.
Method Overriding:Must be same.
3) Return Type:
Method Overloading:Can be same or different.
Method Overriding:Until version 1.4 return type must be same. But from version 1.5 onwards co-variant return types are allowed.
4) Private methods:
Method Overloading:Can be overloaded.
Method Overriding:Cannot be overridden.
5) Static methods:
Method Overloading:Can be overloaded.
Method Overriding:Cannot be overridden.
6) Final methods:
Method Overloading:Can be overloaded.
Method Overriding:Cannot be overridden.
7) Access modifiers:
Method Overloading:No restrictions.
Method Overriding:We can increase the scope of access modifier but we can't reduce the scope.

Comments

Popular posts from this blog

Java 5: Varargs

Difference between "== operator" and "equals() method"