Page 189 - CTS - CSA TP - Volume 2
P. 189

COMPUTER SOFTWARE APPLICATION - CITS




                      // Create an instance of the Cat class
                      Cat myCat = new Cat();


                      // Call the overridden method

                      myCat.makeSound();  // Outputs: Meow!


                      // Call the additional method specific to Cat
                      myCat.purr();  // Outputs: Purring

                  }
              }


           Explanation:
           1.  Base Class (Animal):
              •  Contains a method named makeSound.

           2.  Derived Class (Cat):
              •  Extends the Animal class.
              •  Overrides the makeSound method to provide a specific implementation for the Cat class.
              •  Adds an additional method purr specific to the Cat class.

           3.  Main Class (MethodOverrideExample):
              •  Creates an instance of the Cat class.
              •  Calls the overridden method makeSound, which outputs the specific sound for a cat.
              •  Calls the additional method purr, which is specific to the Cat class.
           In this example, the makeSound method is overridden in the Cat class to provide a more specific implementation
           for a cat’s sound. Method overriding is a key feature in achieving polymorphism in object-oriented programming.
           Instances of the subclass can be treated as instances of the superclass, allowing for flexibility and extensibility in
           code.
           Output:

















            TASK 2 : Here’s a basic example of method overriding in Java
           // Base class (Superclass)
           class Vehicle {

               // Method to display information about the vehicle
               public void displayInfo() {




                                                           174
                                CITS : IT & ITES - Computer Software Application - Exercise 112
   184   185   186   187   188   189   190   191   192   193   194