In Java, it is possible to create methods that have the same name, but different parameter lists and different definitions. This is called as method overloading. Method overloading is used, when objects are required to perform similar tasks, but different input parameters are passed to it. When we call a method in an object, Java matches the method name first and then the number and type of parameters are compared to decide which method definition has to be executed. This process is also known as polymorphism. To create an overloaded method, several different method definitions, all with the same name but with different parameter lists are provided in the class. The different parameter lists may be in terms of either the number or type of arguments. This means that the parameter lists of all the methods with the same name, should be unique, in order to implement method overloading. Method's return type does not play any role in method overloading. Given below is a program, which explains the concept of method overloading: // definition of class mload class mload { // definition of method1 int volume(int i, int j, int k) { return (i * j * k); } // definition of method2 double volume(double a, double b, double c) { return (a * b * c); } // definition of method3 double volume(double a, int b, int c) { return (a * b * c); } // definition of method4 double volume(int a, int b, double c) { return (a * b * c); } } class mOverload { public static void main (String args[]) { mload a1 = new mload(); // method1 is called here System.out.println ("Volume is " + a1.volume(12, 32, 45)); // method3 is called here System.out.println ("Volume is :" + a1.volume(2.2, 4, 3)); // method2 is called here System.out.println ("Volume is: " + a1.volume(1.1, 2.2, 3.3)); // method4 is called here System.out.println ("Volume is : " + a1.volume(1, 2, 3.3)); } } In the above program, four definitions of method volume have been defined in the class mload. When the method volume is called, on the basis of parameters passed, appropriate definition of method volume is executed. |
Course Content > Session 5 >