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

COMPUTER SOFTWARE APPLICATION - CITS



           TASK 2: Let’s explore another example that extends interfaces in Java:

              // Base interface
              interface Animal {
                  void eat(); // Abstract method
              }



              // Extended interface inheriting from Animal
              interface Mammal extends Animal {
                  void giveBirth(); // Additional abstract method
              }



              // Class implementing the extended interface
              class Dog implements Mammal {
                  @Override
                  public void eat() {
                      System.out.println(“Dog is eating”);

                  }


                  @Override
                  public void giveBirth() {

                      System.out.println(“Dog gives birth to puppies”);
                  }
              }


              // Main class

              public class InterfaceExtensionExample2 {
                  public static void main(String[] args) {
                      Dog myDog = new Dog();
                      myDog.eat();

                      myDog.giveBirth();
                  }
              }
           Explanation:
           1  Base Interface (Animal):
              •  Defines a base interface named Animal with a single abstract method eat.

           2  Extended Interface (Mammal):
              •  Extends the Animal interface using the extends keyword.
              •  Introduces an additional abstract method giveBirth.






                                                           182
                                CITS : IT & ITES - Computer Software Application - Exercise 114
   192   193   194   195   196   197   198   199   200   201   202