Page 367 - Computer_Science_F5
P. 367

Computer Science       public void verticalmotion(); // interface method (does not have a body)

                }
                // Hen “implements” the Bird interface
                class Hen implements Bird {
          FOR ONLINE READING ONLY
                  public void birdcries() {

                    // The body of birdcries() is provided here
                    System.out.println(“The hen speak: kooo..kokoko…kookoko”);
                  }
                  public void verticalmotion() {
                    // The body of verticalmotion() is provided here
                    System.out.println(“fyu!fyu!fyu!fyu!fyuuuuu”);
                  }

                }
                class Main {
                  public static void main(String[] args) {
                    Hen myHen = new Hen();  // This create a Hen object
                    myHen.birdcries();

                    myHen.verticalmotion();
                  }
                }


             Output:






                                  Figure 5.26: Output of interface program


           (c) Multiple inheritance using interface

           In Java, multiple inheritance can be achieved using interfaces. Unlike classes, Java
           permits a class to implement multiple interfaces. This allows the class to inherit
           method signatures from multiple interfaces, enabling it to exhibit behavior from
           each interface it implements. This approach avoids the conflicts that can arise with
           multiple  inheritance  in class-based systems, known as the diamond problem. In
           order to implement multiple interfaces, use a comma to separate them. Program
           Example 5.25 shows a multiple interface.

                                                 358
                                                                for Advanced Secondary Schools



     Computer Science Form 5.indd   358                                                     23/07/2024   12:34
   362   363   364   365   366   367   368   369   370   371   372