Method Overloading in Java
If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as sum(int,int) for two parameters, and
add(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behaviour of the method because its name differs. So, we
perform method overloading to figure out the program quickly.
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
Note: In java, Method Overloading is not possible by changing the return type of the
method only.
1) Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of two
numbers and second add() method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for
calling methods.
1. class Adder{
2. static int add(int a,int b) {
3. return a+b;
4. }
5.
6. static int add(int a,int b,int c){
7. return a+b+c;
8. }
9. }
10. class TestOverloading1{
11. public static void main(String[] args){
12. [Link]([Link](11,11));
13. [Link]([Link](11,11,11));
14. }
15. }
Output:
22
33
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
1. class Adder{
2. static int add(int a, int b){
3. return a+b;}
4. static double add(double a, double b){
5. return a+b;}
6. }
7. class TestOverloading2{
8. public static void main(String[] args){
9. [Link]([Link](11,11));
10. [Link]([Link](12.3,12.6));
11. }}
Output:
22
24.9
Q) Why Method Overloading is not possible by changing the return type of method
only?
In Java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static double add(int x,int y){return x+y;}
4. }
5. class TestOverloading3{
6. public static void main(String[] args){
7. [Link]([Link](11,11));//ambiguity
8. }}
Output:
Compile Time Error: method add(int,int) is already defined in class Adder
[Link]([Link](11,11)); //Here, how can java determine which add() method
should be called?
Can we overload java main() method?
Yes, by method overloading. You can have any number of main methods in a class by
method overloading. But JVM calls main() method which receives string array as
arguments only. Let's see the simple example:
1. class TestOverloading4{
2. public static void main(String[] args){[Link]("main with String[]");}
3. public static void main(String args){[Link]("main with String");}
4. public static void main(){[Link]("main without args");}
5. }
Output:
main with String[]
Method Overloading and Type Promotion
One type is promoted to another implicitly if no matching datatype is found. Let's understand
the concept by the figure given below:
As displayed in the above diagram, byte can be promoted to short, int, long, float or double.
The short datatype can be promoted to int, long, float or double. The char datatype can be
promoted to int,long,float or double and so on.
Example of Method Overloading with Type Promotion
1. class OverloadingCalculation1{
2. void sum(int a, long b){[Link](a+b);}
3. void sum(int a,int b,int c){[Link](a+b+c);}
4.
5. public static void main(String args[]){
6. OverloadingCalculation1 obj=new OverloadingCalculation1();
7. [Link](20,20);//now second int literal of the first sum() will be promoted to long
8. [Link](20,20,20);
9.
10. }
11. }
Output:
40
60
If there are matching type arguments in the method, type promotion is not performed.
Example of Method Overloading with Type Promotion in case of ambiguity
If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity.
1. class OverloadingCalculation3{
2. void sum(int a,long b){[Link]("a method invoked");}
3. void sum(long a,int b){[Link]("b method invoked");}
4. public static void main(String args[]){
5. OverloadingCalculation3 obj=new OverloadingCalculation3();
6. [Link](20,20);//now ambiguity
7. }
8. }
Output:
Compile Time Error
One type is not de-promoted implicitly for example double cannot be depromoted to any type
implicitly.
Q) Can a method in sub class overloading a method in super class?
Consider the following example:
1. class P { //Parent / Super Class
2. public void hello() {….}
3. }
4. class Q extends P { Child / Sub Class
5. public void hello(String s) {….}
6. }
When one extends a class, the subclass has access to those methods which are allowed
(e.g. protected, public etc.) defined by superclass. That means the hello() method can be
accessed by the class Q as well. Now, one added a method in class Q with different
parameter (hello(String s)). That means, class Q has access of methods in all with same
name but different parameters and that is "overloading".
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java.
In other words, if a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
Method overriding is used to provide the specific implementation of a method which
is already provided by its superclass.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1. The complete signature of the method must be same i.e.
i. The method in the child class must have the same name as in the parent class
ii. The method in the child class must have the same parameter as in the parent
class.
2. There must be an IS-A relationship (inheritance).
Understanding the problem without method overriding
Let's understand the problem that we may face in the program if we don't use method
overriding. Consider the following code.
1. //Java Program to demonstrate why we need method overriding
2. //Here, we are calling the method of parent class with child class object.
3. //Creating a parent class
4. class Vehicle{
5. void run(){[Link]("Vehicle is running");}
6. }
7. //Creating a child class
8. class Bike extends Vehicle{
9. public static void main(String args[]){
10. //creating an instance of child class
11. Bike obj = new Bike();
12. //calling the method with child class instance
13. [Link]();
14. }
15. }
Output: Vehicle is running
Problem is that one has to provide a specific implementation of run() method in subclass that
is why we use method overriding.
Example of method overriding
In this example, we have defined the run() method in the subclass as defined in the parent
class but it has some specific implementation. The name and parameter of the method are the
same, and there is IS-A relationship between the classes, so there is method overriding.
1. //Java Program to illustrate the use of Java Method Overriding
2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run(){[Link]("Vehicle is running");}
6. }
7. //Creating a child class
8. class Bike2 extends Vehicle{
9. //defining the same method as in the parent class
10. void run(){[Link]("Bike is running safely");}
11.
12. public static void main(String args[]){
13. Bike2 obj = new Bike2();//creating object
14. [Link]();//calling method
15. }
16. }
Output: Bike is running safely
A real example of Java Method Overriding
Consider a scenario where Bank is a class that provides functionality to get the rate of
interest. However, the rate of interest varies according to banks. For example, SBI, ICICI
and AXIS banks could provide 8%, 7%, and 9% rate of interest.
1. //Java Program to demonstrate the real scenario of Java Method Overriding
2. //where three classes are overriding the method of a parent class.
3. //Creating a parent class.
4. class Bank{
5. int getRateOfInterest(){return 0;}
6. }
7. //Creating child classes.
8. class SBI extends Bank{
9. int getRateOfInterest(){return 8;}
10. }
11.
12. class ICICI extends Bank{
13. int getRateOfInterest(){return 7;}
14. }
15. class AXIS extends Bank{
16. int getRateOfInterest(){return 9;}
17. }
18. //Test class to create objects and call the methods
19. class Test2{
20. public static void main(String args[]){
21. SBI s=new SBI();
22. ICICI i=new ICICI();
23. AXIS a=new AXIS();
24. [Link]("SBI Rate of Interest: "+[Link]());
25. [Link]("ICICI Rate of Interest: "+[Link]());
26. [Link]("AXIS Rate of Interest: "+[Link]());
27. }
28. }
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Can we override static method?
No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we
will learn it later.
Why can we not override static method?
It is because the static method is bound with class whereas instance method is bound with an
object. Static belongs to the class area, and an instance belongs to the heap area.
Can we override java main method?
No, because the main is a static method.
Difference between method Overloading and Method Overriding in java
No Method Overloading Method Overriding
.
1) Method overloading is used to increase Method overriding is used to provide the
the readability of the program. specific implementation of the method
that is already provided by its super
class.
2) Method overloading is performed within Method overriding occurs in two classes
class. that have IS-A (inheritance) relationship.
3) In case of method overloading, In case of method overriding, parameter
parameter must be different. must be same.
4) Method overloading is the example of Method overriding is the example of run
compile time polymorphism. time polymorphism.
5) In java, method overloading can't be Return type must be same or covariant in
performed by changing return type of the method overriding.
method only. Return type can be same or
different in method overloading. But you
must have to change the parameter.
Java Access Modifiers with Method Overriding
If you are overriding any method, overridden method (i.e. defined in subclass) must not be
more restrictive.
1. class A{
2. public void msg(){[Link]("Hello java");}
3. }
4.
5. public class Simple extends A{ //child class
6. private void msg(){[Link]("Hello java");} // Will give Compile Time
Error
7. public static void main(String args[]){
8. Simple obj=new Simple();
9. [Link]();
10. }
11. }
The default modifier is more restrictive than protected. That is why, there is a compile-time
error.
Covariant Return Type
Before Java5, it was not possible to override any method by changing the return type. But
now, since Java5, it is possible to override method by changing the return type if subclass
overrides any method whose return type is Non-Primitive but it changes its return type to
subclass type.
Simple example of Covariant Return Type
1. class A{
2. A get(){return this;}
3. }
4. class B1 extends A{
5. B1 get(){return this;}
6. void message(){[Link]("welcome to covariant return type");}
7. public static void main(String args[]){
8. new B1().get().message();
9. }
10. }
Output:
welcome to covariant return type
As you can see in the above example, the return type of the get() method of A class is A but
the return type of the get() method of B class is B. Both methods have different return type
but it is method overriding. This is known as covariant return type.