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

COMPUTER SOFTWARE APPLICATION - CITS




           class Car extends Vehicle {
           // Overriding the accelerate method of the superclass
           @Override
           void accelerate() {

           System.out.println(“Car is accelerating”);
           }
           }
           class Truck extends Vehicle {

           // Overriding the accelerate method of the superclass
           @Override
           void accelerate() {
           System.out.println(“Truck is accelerating”);
           }
           }

           public class VehicleDemo {
           public static void main(String[] args) {
           Vehicle vehicle1 = new Car();
           vehicle1.accelerate(); // Output: Car is accelerating

           Vehicle vehicle2 = new Truck();
           vehicle2.accelerate(); // Output: Truck is accelerating
           }
           }
           Explanation:

           •  In this program, we have a superclass Vehicle and two subclasses Car and Truck.
           •  The Vehicle class has a method named accelerate() that prints “Vehicle is accelerating”.
           •  Both Car and Truck classes extend the Vehicle class and override the accelerate() method with their own
              specific implementations.

           •  In the VehicleDemo class, we create instances of Car and Truck and assign them to references of type
              Vehicle.
           •  When we call the accelerate() method on each object, the overridden version of the method is invoked
              based on the actual object type, demonstrating polymorphism and method overriding.


           TASK 4: Bank Account and its Subclasses

           // Bank Account and its Subclasses using method overriding
           class BankAccount {
           double balance;
           void deposit(double amount) {
           balance += amount;

           }
           void withdraw(double amount) {



                                                           130
                                CITS : IT & ITES - Computer Software Application - Exercise 99
   140   141   142   143   144   145   146   147   148   149   150