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

COMPUTER SOFTWARE APPLICATION - CITS



                   System.out.println(“This is a generic vehicle.”);

               }
           }


           // Derived class (Subclass) extending Vehicle
           class Car extends Vehicle {

               // Override the displayInfo method from the Vehicle class
               @Override
               public void displayInfo() {
                   System.out.println(“This is a car.”);

               }
               // Additional method specific to Car
               public void startEngine() {
                   System.out.println(“Car engine started.”);
               }
           }



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

                   // Create an instance of the Car class
                   Car myCar = new Car();


                   // Call the overridden method
                   myCar.displayInfo();  // Outputs: This is a car.



                   // Call the additional method specific to Car
                   myCar.startEngine();  // Outputs: Car engine started.
               }

           }


           Explanation:
           1  Base Class (Vehicle):
              •  Contains a method named displayInfo to display generic information about the vehicle.
           2  Derived Class (Car):

              •  Extends the Vehicle class.
              •  Overrides the displayInfo method to provide a specific implementation for a car.
              •  Adds an additional method startEngine specific to the Car class.






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