Functional overriding
Function having same name, but different number and type of parameters are called as function overloading. Function overloading also called as compile time polymorphism.
Function overloading Rules:
- Method name must be same in both parent and child class.
- Method should have same number and sequence of parameter.
Function Overloading 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, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.