Chapter 5: Programming to an Interface

 < Day Day Up > 



5.1 Introduction

This chapter introduces the concept of a Java interface. An interface in Java is a definition of behavior to be implemented by objects. Once an interface is defined, components can then be written to take advantage of the behavior promised in the interface. These components can then be reused, as they work with any object that implements the behavior of the interface. This is a type of reuse that we will call generic reuse. [1] Note that an interface is not a data type, which is a collection of data values and operations on those values. An interface is simply a definition of behavior an object must implement to work correctly with an algorithm, collection class, or component. However, like a data type, an interface is checked at compile time to ensure that the objects are valid to be used with the component.

Interfaces are important, as they are basic building blocks for many paradigms, such as many design patterns, algorithm reuse (such as generic sort methods), Java collection classes, and the Java Event Model (Chapter 7). All of these make use of interfaces so that they can work with multiple data types. Interfaces are also important in a number of distributed object technologies, such as RMI (Chapter 13), Enterprise Java Beans (EJB), and the Common Object Request Broker Architecture (CORBA), for which a language called the Interface Definition Language (IDL) was written to specify interfaces.

This chapter presents the topic of interfaces by using two examples. The first creates a special type of collection class, called a SortedPrintTable, which stores sorted data and prints that data in order. This SortedPrintTable class is used to store objects of two different types, Person objects and Car objects, and shows how both can even be stored in the same table. The purpose is to demonstrate that using interfaces allows the programmer to separate the data type from the definition of the behavior of the object. The second example of an interface develops a program that can be used to do simple arithmetic. This program uses a special collection class, called an expression tree, to store arithmetic expressions and to solve them by doing a simple inorder tree walk. This expression tree example is revisited in Chapter 11, where an alternative solution using classification is presented.

[1]Normally, generic reuse is done through parameterized types, such as templates in C++ or generics in Ada. Java does not, at this time, have parameterized types, but they are proposed in JSR 14 [SUN02f].



 < Day Day Up > 



Creating Components. Object Oriented, Concurrent, and Distributed Computing in Java
The .NET Developers Guide to Directory Services Programming
ISBN: 849314992
EAN: 2147483647
Year: 2003
Pages: 162

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net