Interfaces can be used for a couple different reasons, one of which is to work around Java's lack of support for multiple inheritance. The classic example to describe multiple inheritance is the mythical creature Pegasus. Pegasus was a horse that had wings and could fly like a bird. Thus, if you wanted to create a Pegasus class, would you derive it from horse or from bird? It has the abilities of both. In Java, the best way to implement the Pegasus class is to define two interfaces that encapsulate the functionality of a horse and of a bird: HorseLike and BirdLike. Then, define the Pegasus class to implement both interfaces. Listing 8.9 and 8.10 show the definition of the HorseLike and BirdLike interfaces, respectively. Listing 8.9 HorseLike.java public interface HorseLike { public void winee(); public void gallop(); } Listing 8.10 BirdLike.java public interface BirdLike { public void chirp(); public void fly(); } Listing 8.11 shows the implementation of the Pegasus class. Listing 8.11 Pegasus.java public class Pegasus implements HorseLike, BirdLike { public void winee() { System.out.println( "winee!" ); } public void gallop() { System.out.println( "I can run fast!" ); } public void chirp() { System.out.println( "Chirp, chirp!" ); } public void fly() { System.out.println( "Look at me, I'm a flying horse!" ); } } Listing 8.11 shows the Pegasus class implementing both interfaces and providing implementations of all the methods defined by both interfaces. |