Page 144 - CTS - CSA TP - Volume 2
P. 144
COMPUTER SOFTWARE APPLICATION - CITS
class Cat extends Animal {
// Overriding the sound method of the superclass
@Override
void sound() {
System.out.println(“Cat meows”);
}
}
public class AnimalDemo {
public static void main(String[] args) {
Animal animal1 = new Dog();
animal1.sound(); // Output: Dog barks
Animal animal2 = new Cat();
animal2.sound(); // Output: Cat meows
}
}
Output:
Explanation:
• In this program, we have a superclass Animal and two subclasses Dog and Cat.
• The Animal class has a method named sound() that prints “Animal makes a sound”.
• Both Dog and Cat classes extend the Animal class and override the sound() method with their own specific
sound implementations.
• In the AnimalDemo class, we create instances of Dog and Cat and assign them to references of type
Animal.
• When we call the sound() method on each object, the overridden version of the method is invoked based on
the actual object type, demonstrating polymorphism and method overriding.
These examples illustrate how method overriding allows subclasses to provide specialized implementations
of methods inherited from their superclass, enabling polymorphic behavior and code flexibility in Java.
TASK 3: Vehicle and its Subclasses
// Method Overriding
class Vehicle {
void accelerate() {
System.out.println(“Vehicle is accelerating”);
}
}
129
CITS : IT & ITES - Computer Software Application - Exercise 99 CITS : IT & ITES - Computer Software Application - Exercise 99