Page 382 - Computer_Science_F5
P. 382

Method overriding
              Method overriding takes place when a subclass provides a different implementation
              of a method that is already present in its parent class. It allows a subclass to customize
              the behavior of inherited methods, as it is shown in Program Example 5.37.           Chapter Five: Object oriented programming with Java
                         //This code try to overrideREADING ONLY
                    Program Example 5.37:

                Java program to demonstrate method overriding

                     class MotorMachine {
                         public void startEngine() {
                             System.out.println(“MotorMachine starts”);
                         }
                     }
                     class Car extends MotorMachine {
                         // This code try to override
                         public void startEngine() {
                             System.out.println(“Car starts engine using a key”);
                         }
                     }
          FOR ONLINE
                     class Motorcycle extends MotorMachine {

                         public void startEngine() {
                             System.out.println(“Motorcycle starts engine using a kick”);
                         }
                     }
                     public class Main {
                         public static void main(String[] args) {
                             MotorMachine machineA = new Car();
                             MotorMachine machineB = new Motorcycle();


                             machineA.startEngine(); // Output: Car starts engine using a key
                             machineB.startEngine(); // Motorcycle starts engine using a kick
                         }
                     }



              In this particular illustration, there exists a parent class called MotorMachine that
              possesses a  method  named StartEngine().  The  Car and  Motorcycle  classes  are
              derived from the MotorMachine class, and they each provide their own versions of
              the StartEngine() method by overriding it. When we invoke the StartEngine() method

                                                    373
               Student’s Book  Form Five



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