Page 366 - Computer_Science_F5
P. 366

(c) Multiple inheritance in Java         interfaces, which offers certain advantages
              Multiple inheritance is the ability of a   of multiple inheritance without the
              programming language to enable a class   associated complexities. In Java, a class
              to inherit characteristics from more than   can implement multiple interfaces, each of  Chapter Five: Object oriented programming with Java
              one parent class. However, in Java,      which specifies a set of methods that the
          FOR ONLINE READING ONLY
                                                       class must implement. By implementing
              direct support for multiple inheritance   multiple interfaces, a class can inherit
              of classes is not provided. Instead, Java   behaviors from each interface while still
              allows for multiple inheritance using an   adhering to a single inheritance hierarchy.


              Java interfaces
              An interface in Java is a blueprint for a group of related methods without providing
              implementations. In Java, interfaces establish an arrangement for classes by defining
              a  series of method  declarations  without  implementing  them.  Classes implement
              interfaces  by  providing  actual  implementations  for  the  methods  defined  in  the
              interface.


              (a) Interface Declaration
              An interface is declared using the “interface” keyword followed by the interface
              name. This can be presented as:

                    interface Animal {
                        void eat();  //Interface method does not have a body
                        void sleep(); // Interface method does not have a body
                    }


              (b) Implementing an interface

              To implement an interface, a class uses the “implements” keyword followed by the
              interface name.  To utilise the methods defined in an interface, another class must
              “implement” the interface using the implements keyword instead of extends. The
              body of the interface method is provided by the “implement” class, as shown in
              Program Example 5.24.


                      Program Example 5.24:


               Java program for interface

                    // Interface
                   interface Bird {
                     public void birdcries(); // interface method (does not have a body)


                                                    357
               Student’s Book  Form Five



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