Page 383 - Computer_Science_F5
P. 383

Computer Science  on instances of the Car and Motorcycle classes, the overridden methods unique
           to each subclass are executed. This showcases the concept of method overriding,
           which is a form of run-time polymorphism.


           Method overloading
          FOR ONLINE READING ONLY
           Method overloading  permits several  methods to share the same name  while
           possessing distinct parameter lists. It offers a means to define methods that execute
           similar tasks but with varying input types or counts of parameters. The compiler
           selects the appropriate method for invocation based on the arguments supplied to it.
           Program Example 5.38 illustrates the concept.


                 Program Example 5.38:
             Java program to demonstrate method overloading

              public class ArithmeticOperations {

                  // Method to add two integers
                  public int add(int a, int b) {
                      return a + b;
                  }

                  // Method to add three integers
                  public int add(int a, int b, int c) {
                      return a + b + c;
                  }
                  // Method to add two doubles

                  public double add(double a, double b) {
                      return a + b;
                  }

                  // Method to concatenate two strings
                  public String add(String a, String b) {
                      return a + b;
                  }
                  // Method to multiply two integers

                  public int multiply(int a, int b) {
                      return a * b;
                  }



                                                 374
                                                                for Advanced Secondary Schools



     Computer Science Form 5.indd   374                                                     23/07/2024   12:34
   378   379   380   381   382   383   384   385   386   387   388