Java Method Overloading and Overriding – What really differentiates them?

In our last tutorial, we discussed Method Overloading and Method Overriding in Java. Both of them are used to implement polymorphism in Java. But knowing about them is just not enough, you should also know the differences between both of them.

Today in this article, we will discuss the difference between Method Overloading and Overriding in Java with the help of some examples and programs.

What is Method Overloading in Java?

Though the word ‘method’ remains the same in the case of both method overloading and overriding, the main difference comes from the fact that when they are resolved.

Method overloading is resolved during the compilation of the program while method overriding is resolved at the time of execution or during the runtime.

When a class has two or more than two methods which are having the same name but different types of order or number of parameters, it is known as Method Overloading.

Java allows a function to have the same name if it can distinguish them by their number and type of arguments.

For example, the following functions are different in Java:

float divide(int a, int b){...}
float divide( float x, float y){...}
float divide (float a,int b) {...}

That is, the function divide() taking two int arguments is different from divide() taking two float arguments, and also from divide() taking both int and float arguments.

This is called function overloading.

Java Method Overloading

Why Method Overloading?

The main advantage of using method overloading in Java is that it saves time and effort to define a method again and again for performing the same task. In the above example, the three methods are basically performing a division operation.

The names of the methods are the same but the type and number of parameters are different. Method Overloading also helps to implement the static or compile-time polymorphism in Java.

Let us take an example of finding the sum of numbers of integer types. Suppose we want to find the sum number of double types. Then, we can use the concept of method overloading. We will create two or more methods with the same name but different parameters.

Code to illustrate Method/function overloading:

package com.techvidvan.methodoverriding;
public class Addition
{
        int add(int a, int b)
        {
                return (a + b);
        }
        int add(int a , int b , int c)
        {
                return (a + b + c) ;
        }
        double add(double a , double b)
        {
                return (a + b);
        }
        double add(int a , double b)
        {
                return (a + b);
        }
        public static void main( String args[])
        {
                Addition ob = new Addition();

                System.out.println("Calling add method with two int parameters: " +ob.add(17, 25));
                System.out.println("Calling add method with three int parameters: " +ob.add(55, 27, 35));
                System.out.println("Calling add method with two double parameters: " +ob.add(36.5, 42.8));
                System.out.println("Calling add method with one int and one double parameter: " +ob.add(11, 24.5));
        }
}

Output:

Calling add method with two int parameters: 42
Calling add method with three int parameters: 117
Calling add method with two double parameters: 79.3
Calling add method with one int and one double parameter: 35.5

Follow TechVidvan on Google & Stay updated with latest technology trends

Method Overloading Rules

There are some rules which you need to follow for implementing Method Overloading

Rule 1: Change the method signature

The most important rule for method overloading in Java is to change the method signature. The method signature means a number of parameters, types of parameters and the sequence of parameters. At least one of them should be different in order to overload a method.

Code Snippet to understand Rule 1:

public class MyClass
{
    	//Overloaded method
    	public int multiply(int num1, num2)
    	{
    	    	return num1 * num2;
    	}

    	//Overloading method
    	public int multiply(float num1, int num2)	//method with different signature
    	{
    	    	return num1 * num2
    	}
}
Rule 2: Do not consider the Return type of method as a part of the method signature.

Never consider that changing only the return type of the method, the method can be overloaded because the return type is not part of the method signature.

Code Snippet to understand Rule 2:

public class MyClass
{
    	// Overloaded method
    	public int multiply(int num1, num2)
    	{
    	    	return num1 * num2;
    	}

    	// Overloading method
    	public float multiply(int num1, num2) //Not valid because we only chnaged the return type
    	{
    	    	return num1 * num2;
    	}
}
Rule 3: The type of exceptions thrown from the methods are also not considered while overloading a method.

The method overloading is not affected by the type of exceptions thrown by the methods. So whether your overloaded method throws the same exception, a different exception, or does not throw an exception; there is no effect on method overloading.

Code Snippet to understand Rule 3:

public class MyClass
{
    	// Overloaded method
    	public int multiply(int num1, num2) throws NullPointerException
    	{
    	    	return num1 * num2;
    	}

    	// Overloading method
    	public int multiply(int num1, num2) throws Exception
    	//not valid because throwing different type of exception will not lead to method overloadig
    	{
    	    	return num1 * num2;
    	}
}

What is Method Overriding in Java?

Method Overriding is a feature that allows us to redefine the method in the subclass or derived class which is already defined in its parent class or superclass.

In any object-oriented programming language, we can implement Method Overriding only when two classes have ‘is-a’ relationship of inheritance between them.

Which method will be executed depends on the object. If the object of the subclass calls the method, the method of the subclass will override the superclass method and the same method will be executed.

Otherwise, if the superclass object calls the method, the superclass method will be executed.Java Method Overriding

Code to illustrate Method/function overloading:

package com.techvidvan.methodoverriding;
//Base Class
class Parent
{
  void view()
  {
    System.out.println("This is a parent class method");
  }
}
class Child extends Parent
{
  @Override
  void view()
  {
    System.out.println("This is a child class method");
  }
}
//Driver class
public class MethodOverriding
{
  public static void main(String args[])
  {
    Parent obj = new Parent();
    obj.view();
    Parent obj1 = new Child();
    obj1.view();
  }
}

Output:

This is a parent class method
This is a child class method

Here, we can see that a method view() has been overridden in the derived class name Child that is already provided by the base class name Parent.

When we create the instance of class Child and call the view() method, we see that only derived class view() method executes instead of base class method view() and when we create the instance of class Parent and call the view() method, we see that only base class view() method runs instead of derived class method view().

So, it is clear that in method overriding, the method is bound to the objects on the runtime which is decided by the JVM. That’s why it is called Run time polymorphism.

Difference between Method Overloading and Overriding in Java

After having brief knowledge of both the techniques, now we will compare both of them with several parameters.

Comparison of Method overloading and overriding

ParameterMethod OverloadingMethod Overriding
PolymorphismMethod Overloading is used to implement Compile time or static polymorphism.Method Overriding is used to implement Runtime or dynamic polymorphism.
PurposeIt is used to expand the readability of the program.It is used to give the specific implementation of the method which is already provided by its base class
Parameter ListParameters of the overloaded function must be different in either number or type in case of method overloadingThe number of parameters and type of each parameter must be the same in case of method overriding.
Number of ClassesIt occurs within the same classIt is performed within two classes with an inheritance relationship.
InheritanceIt may or may not be required for Method OverloadingIt is must for Method Overriding
Return TypeThe return type may or may not be the same, but we have to change the parameter.Here, the return type must be either the same or of the covariant type.
static, final and private methodsWe can overload a static, final or private method in Method OverloadingWe can not override a static, final or private method in Method Overriding
BondStatic BindingDynamic Binding
SpeedIt is fastIt is slower
SignatureThe signature must be differentThe signature must be the same
AssociationIt is usually associated with static programs.It is usually associated with object-oriented programs.
PerformanceOverloading gives better performance than overridingLesser  Performance than Overloading because the binding of the overridden method is done at the runtime.
Access ModifierAny access modifier can be used while overloading the methods The level of access should be either the same or with a wider scope.
ExceptionsMay throw different exceptions.May reduce or eliminate exceptions. But, must not throw new or broader checked exceptions but can throw narrower checked exceptions.

Summary

Method Overloading and Method Overriding are the two very essential concepts of Object-Oriented Programming. Both are used to support the concept of Polymorphism in Java.

In this article, we learned about the basic differences between Method overloading and Method Overriding in Java with the help of examples and programs. This article will surely help you to compare both the techniques.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google | Facebook


1 Response

  1. Vijayanand Vijay Jayamani says:

    i partially feel happy about your java tutorial because i could understand what is oops concepts in java among all the tutorial websites really its perfect for beginners and experts . THANKS TO TECHVIDVAN.

    IF YOU DONT PLEASE SEND SOME EXISTING PROJECTS IN JAVA WITH CODING PART FOR PRACTICE. THANKS AND REGARDS
    VIJAY VICTOR

Leave a Reply

Your email address will not be published. Required fields are marked *