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

COMPUTER SOFTWARE APPLICATION - CITS




             // Concrete class 2
             class Cat extends Animal {
                 // Implementing abstract methods

                 @Override
                 public void makeSound() {
                     System.out.println(“Meow!”);
                 }



                 @Override
                 public void eat() {
                     System.out.println(“Cat is eating”);
                 }

             }


             // Main class
             public class AnimalExample {
                 public static void main(String[] args) {

                     // Create instances of concrete classes
                     Dog myDog = new Dog();
                     Cat myCat = new Cat();


                     // Call abstract and concrete methods

                     myDog.makeSound();
                     myDog.eat();
                     myDog.sleep();



                     myCat.makeSound();
                     myCat.eat();
                     myCat.sleep();
                 }
             }
           Explanation:

           1.  Abstract Class (Animal):
             •  Declares two abstract methods makeSound() and eat().
             •  Defines a concrete method sleep() with a default implementation.
           2.  Concrete Classes (Dog and Cat):

             •  Extend the abstract class Animal.
             •  Provide implementations for the abstract methods makeSound() and eat().





                                                           166
                                CITS : IT & ITES - Computer Software Application - Exercise 110
   176   177   178   179   180   181   182   183   184   185   186