Providing Callbacks via Interfaces

Problem

You want to provide callbacks ; that is, have unrelated classes call back into your code.

Solution

One way is to use a Java interface.

Discussion

An interface is a class-like object that can contain only abstract methods and final fields. As we’ve seen, interfaces are used a lot in Java! In the standard API, the following are a few of the commonly used interfaces:

  • Runnable, Comparable, and Cloneable (in java.lang)

  • List, Set, Map, and Enumeration/Iterator (in the Collections API; see Chapter 7)

  • ActionListener, WindowListener, and others (in the AWT GUI; see Section 13.5)

  • Driver, Connection, Statement, and ResultSet (in JDBC; see Section 20.4)

  • The "remote interface” -- the contact between the client and the server -- is specified as an Interface (in RMI, CORBA, and EJB)

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.