Let us see what Method Overloading is in java & how do we use it…
- Two or more methods in a class can have the same name, if their argument lists are different
- Argument list could differ in –
- Number of parameters
- Data type of parameters
- Sequence of data type of parameters
- This feature we call it as Method Overloading/Static Polymorphism
- Overloading in java occurs when methods in a same class or in child classes shares a same name with a ‘difference in number of arguments’ or ‘difference in argument type’ or both.
Now, let me ask all of you few questions:
- Can method overloading occur between methods in a parent class and that of the child class?
- Answer: Yes, absolutely.
- Does method overloading depend upon the return type of the methods
- Answer: No.
Method Overloading Examples:
- Example 1 – Difference in number of parameters
Output: 1st method
- Example 2 – Another example to show methods in child classes can also have method overloading
Output: 2nd method
Now, let us see the cases in which Method overloading is not performed –
Methods having same name in one class or in child class could not perform method overloading if they are just different in:
1) Name of argument, and not in number of arguments or type of arguments.
2) Having different return type only.
- At this point of time, many of you might be thinking How method overloading helps in java or I can say Why we need method overloading?
There are 2 points which comes out –
- It helps in maintaining consistency in method naming, doing same task with just a difference of input parameter.
- Helps in reducing overhead of remembering the name of different functions for same task, instead what we can do is we can pass different type or number of parameters to a single overloaded method/function.
Example –
public class ABC
{
public Employee getEmpById(int empId)
{
}
public Employee getEmpByName(int empName)
{
}
public Employee getEmpByDob(int empDob)
{
}
}
/*It’s better to overload methods with same functionality, this make the
code consistent and reduce overhead of remember method names with
different type and number of input parameter.*/
Instead write the code as –
public class ABC
{
public Employee getEmp(int empId)
{
}
public Employee getEmp(int empName)
{
}
public Employee getEmp(int empDob)
{
}
}
One important point to note:
- We can overload static and final method in java but we can’t override static method.
At the end, a small refresher on the interview questions related to overloading which might be asked from the java developers –
- Can main() method be overloaded in java?
- Answer: Yes. The main() method can be overload. But if you change the signature of the main method, the entry point for the program will be dimnished.
Post a Comment