The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Interfaces and Packages

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(TickerSymbol tickerSymbol,
                             BigDecimal newValue) {
        switch (tickerSymbol) {
            case SUNW:
                ...
                break;
            case ORCL:
                ...
                break;
            case CSCO:
                ...
                break;
            default:
                // handle unknown stocks
                ...
                break;
        }
    }
}
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 signature — the name and the number and type of arguments — in 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 applets display or otherwise uses this information.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.