Creating and Using Interfaces

The section What Is an Interface? (page 54) provided an introduction to interfaces. This section goes further, showing you how to create and to use interfaces and talking about why you would use an interface instead of a class.

An interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. An interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behavior.

Definition

An interface is a named collection of method definitions (without implementations). An interface can also declare constants.

Because an interface is simply a list of unimplemented, and therefore abstract, methods, you might wonder how an interface differs from an abstract class. The differences are significant.

  • An interface cannot implement any methods, whereas an abstract class can.
  • A class can implement many interfaces but can have only one superclass.
  • An interface is not part of the class hierarchy. Unrelated classes can implement the same interface.

Let's set up the example we'll be using in this section. Suppose that you have written a class that can watch stock prices coming over a data feed. This class allows other classes to register to be notified when the value of a particular stock changes. First, your class, which we'll call StockMonitor, would implement a method that lets other objects register for notification:

public class StockMonitor { 
 public void watchStock(StockWatcher watcher, 
 String tickerSymbol, double delta) { 
 ... 
 } 
} 

The first argument to this method is a StockWatcher object. StockWatcher is the name of an interface whose code you will see in the next section. That interface declares one method: valueChanged. An object that wants to be notified of stock changes must be an instance of a class that implements this interface and thus implements the valueChanged method. The other two arguments provide the symbol of the stock to watch and the amount of change that the watcher considers interesting enough to be notified of. When the StockMonitor class detects an interesting change, it calls the valueChanged method of the watcher.

The watchStock method ensures, through the data type of its first argument, that all registered objects implement the valueChanged method. It makes sense to use an interface data type here because it matters only that registrants implement a particular method. If StockMonitor had used a class name as the data type, that would artificially force a class relationship on its users. Because a class can have only one superclass, it would also limit what type of objects can use this service. By using an interface, the registered object's class could be anythingApplet or Thread, for instancethus allowing any class anywhere in the class hierarchy to use this service.

Defining an Interface

Figure 69 shows that an interface definition has two components: the interface declaration and the interface body. The interface declaration declares various attributes about the interface, such as its name and whether it extends other interfaces. The interface body contains the constant and the method declarations for that interface.

Figure 69. The StockWatcher interface and the structure of an interface definition.

graphics/06fig01.gif

public interface StockWatcher { 
 final String sunTicker = "SUNW"; 
 final String oracleTicker = "ORCL"; 
 final String ciscoTicker = "CSCO"; 
 void valueChanged(String tickerSymbol, double newValue); 
} 

The interface shown in Figure 69 is the StockWatcher interface mentioned previously. This interface defines three constants, which are the ticker symbols of watchable stocks. This interface also declares, but does not implement, the valueChanged method. Classes that implement this interface provide the implementation for that method.

The Interface Declaration

Figure 70 shows all possible components of an interface declaration.

Figure 70. The possible components of an interface declaration and their purposes.

graphics/06fig02.gif

Two elements are required in an interface declarationthe interface keyword and the name of the interface. The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that your interface is public, your interface will be accessible only to classes that are defined in the same package as the interface.

An interface declaration can have one other component: a list of superinterfaces. An interface can extend other interfaces, just as a class can extend or subclass another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces. The list of superinterfaces is a comma-separated list of all the interfaces extended by the new interface.

The Interface Body

The interface body contains method declarations for all the methods included in the interface. A method declaration within an interface is followed by a semicolon (;) because an interface does not provide implementations for the methods declared within it. All methods declared in an interface are implicitly public and abstract.

An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final.

Member declarations in an interface disallow the use of some declaration modifiers; you cannot use transient, volatile, or synchronized in a member declaration in an interface. Also, you may not use the private and protected specifiers when declaring members of an interface.

Note

Previous releases of the Java platform allowed you to use the abstract modifier on interface declarations and on method declarations within interfaces. However, this is unnecessary, because interfaces and their methods are implicitly abstract. You should not use abstract in your interface declarations or in your method declarations within interfaces. public Makes this interface public.

 

Implementing an Interface

An interface defines a protocol of behavior. A class that implements an interface adheres to the protocol defined by that interface. To declare a class that implements an interface, include an implements clause in the class declaration. Your class can implement more than one interface (the Java platform supports multiple inheritance for interfaces), so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.

By Convention

The implements clause follows the extends clause, if it exists.

Here's a partial example of an applet that implements the StockWatcher interface:

public class StockApplet extends Applet implements StockWatcher { 
 ... 
 public void valueChanged(String tickerSymbol, double newValue) { 
 if (tickerSymbol.equals(sunTicker)) { 
 ... 
 } else if (tickerSymbol.equals(oracleTicker)) { 
 ... 
 } else if (tickerSymbol.equals(ciscoTicker)) { 
 ... 
 } 
 } 
} 

Note that this class refers to each constant defined in StockWatcher, sunTicker, oracleTicker, and ciscoTicker, by its simple name. Classes that implement an interface inherit the constants defined within that interface. So those classes can use simple names to refer to the constants. Any other class can use an interface's constants with a qualified name, like this:

StockWatcher.sunTicker 

When a class implements an interface, it is essentially signing a contract. Either the class must implement all the methods declared in the interface and its superinterfaces, or the class must be declared abstract. The method signaturethe name and the number and type of argumentsin the class must match the method signature as it appears in the interface. The StockApplet implements the StockWatcher interface, so the applet provides an implementation for the valueChanged method. The method ostensibly updates the applet's display or otherwise uses this information.

Using an Interface as a Type

When you define a new interface, you are defining a new reference data type. You can use interface names anywhere you can use any other data type name. Recall that the data type for the first argument to the watchStock method in the StockMonitor class is StockWatcher:

public class StockMonitor { 
 public void watchStock(StockWatcher watcher, 
 String tickerSymbol, double delta) { 
 ... 
 } 
} 

Only an instance of a class that implements the interface can be assigned to a reference variable whose type is an interface name. So only instances of a class that implements the StockWatcher interface can register to be notified of stock value changes. StockWatcher objects are guaranteed to have a valueChanged method.

Interface Cannot Grow

Suppose that you want to add some functionality to StockWatcher. For instance, suppose that you want to add a method that reports the current stock price, regardless of whether the value changed:

public interface StockWatcher { 
 final String sunTicker = "SUNW"; 
 final String oracleTicker = "ORCL"; 
 final String ciscoTicker = "CSCO"; 
 void valueChanged(String tickerSymbol, double newValue); 
 void currentValue(String tickerSymbol, double newValue); 
} 

However, if you make this change, all classes that implement the old StockWatcher interface will break because they don't implement the interface anymore! Programmers relying on this interface will protest loudly.

Try to anticipate all uses for your interface up front and specify it completely from the beginning. Given that this is often impossible, you may need either to create more interfaces later or to break your customer's code. For example, you could create a StockWatcher subinterface called StockTracker that declared the new method:

public interface StockTracker extends StockWatcher { 
 void currentValue(String tickerSymbol, double newValue); 
} 

Now users of your code can choose to upgrade to the new interface or to stick with the old interface.

Summary of Interfaces

An interface defines a protocol of communication between two objects. An interface defini tion is comprised of a declaration and a body. The section The Interface Declaration (page 230) shows all possible components of an interface declaration. The interface body contains declarations, but no implementations, for a set of methods. An interface might also contain constant definitions. A class that implements an interface must implement all the methods declared in the interface. An interface name can be used anywhere a type can be used.

Questions and Exercises: Interfaces

Questions

1:

What methods would a class that implements the java.util.Iterator interface [1] have to implement?

[1] Iterator was introduced to the Java platform in the 1.2 release. If you are using a prior release, answer this question with regard to the Enumerator interface instead.

2:

What is wrong with the following interface?

public interface SomethingIsWrong { 
 public void aMethod(int aValue) { 
 System.out.println("Hi Mom"); 
 } 
} 
3:

Fix the interface in question 2.

4:

Is the following interface valid?

public interface Marker { 
} 

Exercises

1:

Write a class that implements the Iterator interface found in the java.util package. The ordered data for this exercise is the 13 cards in a suit from a deck of cards. The first call to next returns 2, the subsequent call returns the next highest card, 3, and so on, up to Ace. Write a small main method to test your class.

2:

Suppose that you have written a time server, which periodically notifies its clients of the current date and time. Write an interface that the server could use to enforce a particular protocol on its clients.

Answers

You can find answers to these Questions and Exercises online:

http://java.sun.com/docs/books/tutorial/java/interpack/QandE/interfaces-answers.html

Getting Started

Object-Oriented Programming Concepts

Language Basics

Object Basics and Simple Data Objects

Classes and Inheritance

Interfaces and Packages

Handling Errors Using Exceptions

Threads: Doing Two or More Tasks at Once

I/O: Reading and Writing

User Interfaces That Swing

Appendix A. Common Problems and Their Solutions

Appendix B. Internet-Ready Applets

Appendix C. Collections

Appendix D. Deprecated Thread Methods

Appendix E. Reference



The Java Tutorial(c) A Short Course on the Basics
The Java Tutorial: A Short Course on the Basics, 4th Edition
ISBN: 0321334205
EAN: 2147483647
Year: 2002
Pages: 125

Similar book on Amazon

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