Method Overloading in Java

Method Overloading in Java

1. Method Overloading

Method overloading is a form of polymorphism in Java, where a class can have multiple methods with the same name but different parameter lists. This feature enables you to perform operations using the same name methods with different parameters which enhance code readability and flexibility.

 When a method is invoked, the Java compiler or runtime environment determines the appropriate method to call based on the arguments provided during the method call.

Method overloading is a form of compile-time polymorphism, where the decision about which method to call is made at compile time based on the method’s signature (name and parameter types), not at runtime.

Example 

package com.rtt.learn;


public class TestOverload {
	
 public void test() {
	 System.out.println("Method overloading:  Method name 'test' with no argument");
 }
 
 public void test(String name) {
	 System.out.println("Method overloading:  Method name 'test' with 1 String argument. passing argument :" + name);
 }
 
 public String test(String name, String slogan) {
	 String str =  name + " " + slogan;
	 System.out.println("Method overloading:  Method name 'test' with 2 String arguments. name =" + name + ": slogan =" + slogan);
	 return str;
			
 }

 private void test(String name, int age) {
	 System.out.println("Method overloading:  Method name 'test' with 2 arguments: String and int. passing arguments: Name =" + name +" age="+age);
			
 }

 public static void main(String[] args) {
	TestOverload testOverload = new TestOverload();
	testOverload.test();
	testOverload.test("RoundTheTech !!");
	String returnedStr = testOverload.test("RoundTheTech " , "Let Us Learn Together");
	System.out.println("returned String is " + returnedStr);
	testOverload.test("RoundTheTech ", 3 );
}
 
}


Output:

Method overloading:  Method name 'test' with no argument
Method overloading:  Method name 'test' with 1 String argument. passing argument :RoundTheTech !!
Method overloading:  Method name 'test' with 2 String arguments. name =RoundTheTech : slogan =Let Us Learn Together
returned String is RoundTheTech  Let Us Learn Together
Method overloading:  Method name 'test' with 2 arguments: String and int. passing arguments: Name =RoundTheTech  age=3

2. Types of Method Overloading:

Method Overloading can be achieved by using two ways : 

  1. Using Different Parameter Types
  2. Using Different Number of Parameters:

2.1. Different Parameter Types

Overloaded methods have parameters with different data types. For example:

Example : Overloaded test() is written using different type of parameters

package com.rtt.learn;


public class TestOverload {
	
 public void test( double salary,  int age) {
	 System.out.println("Method overloading with different argument type. Salary =" + salary + " age = "+age);
 }

 public String test(String name, double salary) {
	 System.out.println("Method overloading with different argument type. name =" + name + " salary = "+salary);
	 return name+" " + salary;
 }

 private void test(String name, int age) {
	 System.out.println("Method overloading with different argument type. name =" + name + " age = "+age);
			
 }

 public static void main(String[] args) {
	TestOverload testOverload = new TestOverload();
	testOverload.test(10000.55, 24);
	String returnedStr = testOverload.test("RoundTheTech", 10000.55);
	System.out.println("returned String is " + returnedStr);
	 testOverload.test("RoundTheTech" , 24);
	}
 
}

Output:

Method overloading with different argument types. Salary =10000.55 age = 24
Method overloading with different argument types. name =RoundTheTech salary = 10000.55
returned String is RoundTheTech 10000.55
Method overloading with different argument types. name =RoundTheTech age = 24

2.2 Different Number of Parameters:

Overloaded methods have a different number of parameters. For example:

Example : Overloaded test() written with no argument, and different number of arguments

package com.rtt.learn;


public class TestOverload {
	
 public void test() {
	 System.out.println("Method overloading with Different Number of Parameters. no argument method");
 }

 public void test(String name) {
	 System.out.println("Method overloading with Different Number of Parameters. 1 parameter name =" + name);
 }

 public String test(String name, String slogan) 
	 String str =  name + " " + slogan;
	 System.out.println("Method overloading with Different Number of Parameters. 2 parameters name =" + name + ": slogan =" + slogan);
	 return str;
			
 }

public static void main(String[] args) {
	TestOverload testOverload = new TestOverload();
	testOverload.test();
	testOverload.test("RoundTheTech !!");
	String returnedStr = testOverload.test("RoundTheTech " , "Let Us Learn Together");
	System.out.println("returned String is " + returnedStr);

}
 
}


Output:

Method overloading with Different Number of Parameters. no argument method
Method overloading with Different Number of Parameters. 1 parameter name =RoundTheTech !!
Method overloading with Different Number of Parameters. 2 parameters name =RoundTheTech : slogan =Let Us Learn Together
returned String is RoundTheTech  Let Us Learn Together

3. Points to Remember while Method Overloading

  1. Parameter Differentiation: Overloaded methods must have different parameter lists, either in terms of the number of parameters or in terms of their types. 

  2. Return Type: Method overloading is determined solely by the method name and parameter(s), not
    the return type. Overloaded methods can have same or different return types.

  3. Modifier : There is no impact of modifier since method overloading base is method name and its parameter.

  4. Ambiguity:  Method overloading is determined basically by the method name and parameter(s) but if you try to overload a method with the same name and parameter it will result in compilation error.

4. Can main() Method Be Overloaded? 

Yes, the main method can be overloaded in the class by defining additional main methods with different parameter(s). 

While run the program, JVM invokes only standard main method having syntax  public static void main(String[] args).

Other overloaded main method(s) will be invoked on request basis.

5. Benefits of Method Overloading

Code Readability: Method overloading improves code readability by providing a uniform method name for related operations that makes the codebase more intuitive to understand. Like  sum() methods in a class that can be used to get sum of 2 or more numbers numbers, or of different data types or arguments

Like : 

int sum(int... args) { }
  double sum(double... args)  {}

Reduced Code Duplication: Instead of creating separate methods with distinct names for similar tasks, method overloading allows developers to consolidate functionality and reduce code redundancy.

Like:

 int sum(int... args) {
	 int sum = 0;
	 for(int a : args) {
		 System.out.println("a:::"+a);
		 sum = sum + a;
	 }
	 return sum;
 }

  double sum(double... args) {
	  double sum = 0;
		 for(double a : args) {
			 sum = sum + a;
		 }
		 return sum;
	 }

Flexibility: By accommodating different data types and parameter combinations, method overloading enhances the flexibility of classes, enabling them to handle different scenarios. As You can see in above example same name method can be utilized for deterrent arguments.

Easier Maintenance: When changes are needed, modifying a single method rather than several methods with similar purposes simplifies maintenance and reduces the likelihood of introducing errors.

Like in this example: logic change to get address for different arguments getAddress() will be at one place and reflect for each overloaded method. Which is easy to maintain.

package com.rtt.learn;


public class TestOverload {
	
	  String getAddress(String flat, String society, String city) {
		 
		  return getAddress(flat, society, city, null);
		  
	 }	

	  String getAddress(String society, String city) {
			 
		  return getAddress(null, society, city, null);  
	 }	
	
  String getAddress(String flat, String society, String city, String state) {
	  StringBuilder strBuild = new StringBuilder();
	  
	 if(null != flat) strBuild.append("Flat : " +flat);
	 if(null != society) strBuild.append(" Society : " +society);
	 if(null != city)strBuild.append(" City : " +city);
	 if(null != state)strBuild.append(" State :" + state);
	 
	  return strBuild.toString();
	  
 }
  
 public static void main(String[] args) {
	TestOverload testOverload = new TestOverload();
	System.out.println("Address ="+ testOverload.getAddress("gs", "MBD"));
	System.out.println("Address ="+ testOverload.getAddress("000", "gs", "MBD"));
	
}
 
}

6. Difference Between Method Overloading and Method Overriding

AspectMethod OverloadingMethod Overriding
DefinitionSame name methods with different parameter(s) in the same class.Overriding is related to super class and subclass relationships. Same name method(s) with same parameter(s) and return type in the child class.
Inheritance RequiredNot dependent on inheritance. Can be applied to a single class.It requires inheritance. Involves a superclass-subclass relationship.
Method SignatureMethod names are the same, but parameter types or numbers of parameters can be different.Method names, parameter types, and return types must be identified in child class as in parent class.
BindingResolved at compile time (static binding) based on method signature.Resolved at runtime (dynamic binding) based on the actual object type.
Use CaseUsed for creating multiple methods for different parameter scenarios in a single class.Used to specialize and customize behavior of inherited methods in subclasses.
Examplejava class Calculator { int sum(int a, int b) { return a + b; } double sum(double a, double b) { return a + b; } }java class Shape { void draw() { System.out.println(“Drawing a shape”); } } class Circle extends Shape { @Override void draw() { System.out.println(“Drawing a circle”); } }

P.S. We welcome your feedback. Please comment, if you find anything incorrect, or want to share more information about the topic or want to share any kind of feedback.

Leave a Reply

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