Chapter 9. Interfaces and Polymorphism

CHAPTER GOALS

  • To be able to declare and use interface types

  • To understand the concept of polymorphism

  • To appreciate how interfaces can be used to decouple classes

  • To learn how to implement helper classes as inner classes

    G To implement event listeners in graphical applications

In order to increase programming productivity, we want to be able to reuse software components in multiple projects. However, some adaptations are often required to make reuse possible. In this chapter, you will learn an important strategy for separating the reusable part of a computation from the parts that vary in each reuse scenario. The reusable part invokes methods of an interface. It is combined with a class that implements the interface methods. To produce a different application, you simply plug in another class that implements the same interface. The program's behavior varies according to the implementation that is plugged in—this phenomenon is called polymorphism.

Using Interfaces for Algorithm Reuse

It is often possible to make a service available to a wider set of inputs by focusing on the essential operations that the service requires. Interface types are used to express these common operations.

Consider the DataSet class of Chapter 6. That class provides a service, namely computing the average and maximum of a set of input values. Unfortunately, the class is suitable only for computing the average of a set of numbers. If we wanted to process bank accounts to find ...

Get Big Java, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.