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): Usage: s = Student(); |
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(){ The second method, which expects a single integer argument, resets each grade to that integer. public void resetGrades(int 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){ Usage: Student s = new Student(); |