3 Method Overloading
3 Method Overloading
CSA6003T
BHAWANA BOTHARA
ASSISTANT PROFESSOR
LEARNING OBJECTIVES
• In Java, it is possible to define two or more methods within the same class
that share the same name, as long as their parameter declarations are
different. When this is the case, the methods are said to be overloaded, and
the process is referred to as method overloading.
• Method overloading is one of the ways that Java supports polymorphism.
• Method overloading is an example of compile time polymorphism.
WHY DO WE NEED OVERLOADING
• If we have to perform only one operation, having same name of the methods
increases the readability of the program.
• Suppose you have to perform addition of the given numbers but there can be
any number of arguments, if you write the method such as a(int,int) for two
parameters, and b(int,int,int) for three parameters then it may be difficult for
you as well as other programmers to understand the behavior of the method
because its name differs.
DIFFERENT WAYS TO OVERLOAD THE
METHOD
• Method overloading in Java is a powerful feature that enables a class to have multiple methods
with the same name but different parameter lists, enhancing code readability and usability. By
allowing methods to differ by the type, number, or order of parameters, overloading facilitates
the handling of various data inputs under a single method name. This technique exemplifies
compile-time polymorphism, improving code flexibility and reusability. Key rules include
maintaining the same method name and ensuring different parameter lists, while return type
does not determine overloading. Practical applications, such as overloading methods in an ATM
system for different withdrawal scenarios, highlight its real-world benefits. Overall, method
overloading streamlines code management and increases functionality without sacrificing
clarity.
ASSESSMENT
1. Which of the following is true about method overloading?
A. Same parameter types.
B. Different method names.
C. Different parameter lists.
2. Method overloading is an example of ________ polymorphism.
Answer: Compile-time
3. In method overloading, methods must have the same ______ but different ________.
Answer: Name, parameters
4. True or False: Method overloading can have different return types.
Answer: True
ASSESSMENT
5. Which of the following cannot be used to differentiate overloaded methods?
A. Number of parameters
B. Type of parameters
C. Order of parameters
D. Return