Method Overloading
Python |
Java |
Method overloading is
accomplished by using optional and default parameters or by checking the type
of the parameters and responding appropriately. For example, a Student class might have three methods named resetGrades for resetting all the grades. The first method,
which expects no arguments, resets each grade to 0. The second method,
which expects a single integer argument, resets each grade to that integer. The third method,
which expects a list of integers as an argument, resets the grades to these
integers at the corresponding positions in the list. To accomplish this, a
single method with a single optional parameter is defined. When the method is called, the value
of this parameter will be either 0 (no argument was given), an integer
(whatever new grade to assign all the grades), or a list of integers. If the type of the parameter is a
list, the method uses an index to fetch the grade from the list. Otherwise, the method uses the value
directly. def resetGrades(value
= 0): for i in
range(Student.NUM_GRADES):
if type(value) == list:
self.grades[i] = value[i]
else:
self.grades[i] = value Usage: s =
Student(); s.resetGrades(100) s.resetGrades() newGrades =
[85, 66, 90, 100, 73] s.resetGrades(newGrades) |
A methodŐs signature
consists of its name and parameter types. The return type is not included in the signature. Two methods are overloaded if they
have the same name but different signatures. For example, a Student class might have three methods named resetGrades for resetting all the grades. All are distinct methods. The first method,
which expects no arguments, resets each grade to 0: public void
resetGrades(){ resetGrades(0); } The second method,
which expects a single integer argument, resets each grade to that
integer. public void
resetGrades(int grade){ for (int i = 0; i <
Student.NUM_GRADES; i++)
this.grades[i] = grade; } The third method,
which expects an array of integers, resets the grades to these integers in
the corresponding positions in the array. public void
resetGrades(int[] grades){ for (int i = 0; i <
Student.NUM_GRADES; i++)
this.grades[i] = grades[i]; } Usage: Student s =
new Student(); s.resetGrades(100); s.resetGrades(); int[]
newGrades = {85, 66, 90, 100, 73}; s.resetGrades(newGrades); |