Java Function overloading

Java function having same name, but different number and type of parameters are called as Java function overloading. Function overloading also called as compile time polymorphism.

Function overloading Rules:

  1. Method name must be same in both parent and child class.
  2. Method should have same number and sequence of parameter.

Examples:

Below are the examples of add function overloading with different parameter:

By changing number of parameters.

If we perform addition of different numbers will lead us to create overloaded function. In below example, we setting an expectation to add numbers.

if we pass one parameter, the first one function will get call add (int a) and return the processed value which will be a+1.

similarly, if we are passing two values as a function parameter will call add (int a, int b)and return the processed value which will be a+b addition.

add (int a) {
return a + 1;
}
add (int a, int b) {
return a + b;
}
add (int a, int b, int c) {
return a + b + c;
}

By changing data type in the parameters:

Below is the example for addition of two int and float variables:

add (int a, int b) {
return a + b;
}
add (float a, float b) {
return a + b;
}

Q. Overload method with different return type is possible in Java?

Ans. Method overloading is not possible by changing only the return type of the method. It is not allowed in java to create method with the exact same number and sequence of parameters.

Q. Is main method overloading allowed in Java?

Ans.ย Yes. The main method overloading in allowed. But, at runtime compiler will call method having string an array as a parameter.

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

๐ŸŒ LinkedIn

๐Ÿ“ Blogs

๐Ÿ“ง Imran Khan