Page 356 - CITS - Computer Software Application -TT
P. 356

COMPUTER SOFTWARE APPLICATION - CITS



               }

               // Method with object as parameter
               public void myMethod(MyClass obj) {
                   // block of code to define this method
               }
               // More methods

           }

           Java Method Overloading

           In Java, two or more methods may have the same name if they differ in parameters (different number of parameters,
           different types of parameters, or both). These methods are called overloaded methods and this feature is called
           method overloading.
           Why method overloading?
           Suppose, you have to perform the addition of given numbers but there can be any number of arguments (let’s say
           either 2 or 3 arguments for simplicity).
           In order to accomplish the task, you can create two methods sum2num(int, int) and sum3num(int, int, int) for two
           and three parameters respectively. However, other programmers, as well as you in the future may get confused
           as the behavior of both methods are the same but they differ by name.
           The better way to accomplish this task is by overloading methods. And, depending upon the argument passed,
           one of the overloaded methods is called. This helps to increase the readability of the program
           How to perform method overloading in Java?
           Here are different ways to perform method overloading:
           class MethodOverloading {

               private static void display(int a){
                   System.out.println(“Arguments: “ + a);
               }
               private static void display(int a, int b){
                   System.out.println(“Arguments: “ + a + “ and “ + b);

               }
               public static void main(String[] args) {
                   display(1);
                   display(1, 4);

               }
           }
           Output:
           Arguments: 1
           Arguments: 1 and 4
           Important Points

           •  Two or more methods can have the same name inside the same class if they accept different arguments. This
              feature is known as method overloading.
           •  Method overloading is achieved by either:





                                                           343

                             CITS : IT&ITES - Computer Software Application - Lesson 94 - 100
   351   352   353   354   355   356   357   358   359   360   361