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

COMPUTER SOFTWARE APPLICATION - CITS



           EXERCISE 112 : Override methods in JAVA



            Objectives

           At the end of this exercise you shall be able to
           •  develop Java programs to  Override methods in JAVA.


           Requirements

           Tools/Materials
           •  PC / laptop with windows OS
           •   SDK software
           •  Test editor (Visual studio/ subline/ notepad)

           Procedure

           In Java, method overriding is a mechanism by which a subclass provides a specific implementation of a method
           that is already provided by its superclass. The overridden method in the subclass should have the same signature
           (name, return type, and parameters) as the method in the superclass.

           TASK 1: Here’s a basic example of method overriding in Java:
              // Base class (Superclass)
              class Animal {
                  // Method to make a sound
                  public void makeSound() {
                      System.out.println(“Some generic animal sound”);

                  }
              }
              // Derived class (Subclass) extending Animal
              class Cat extends Animal {

                  // Override the makeSound method from the Animal class
                  @Override
                  public void makeSound() {
                      System.out.println(“Meow!”);
                  }



                  // Additional method specific to Cat
                  public void purr() {
                      System.out.println(“Purring...”);
                  }

              }
              // Main class to demonstrate method overriding
              public class MethodOverrideExample {
                  public static void main(String[] args) {





                                                           173
 CITS : IT & ITES - Computer Software Application - Exercise 111
   183   184   185   186   187   188   189   190   191   192   193