Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
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 theimplements
keyword is followed by a comma-separated list of the interfaces implemented by the class.
By Convention: Theimplements
clause follows theextends
clause, if it exists.
Here's a partial example of an applet that implements the
StockWatcher
interface:
Note that this class refers to each constant defined inpublic 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)) { ... } } }StockWatcher
,sunTicker
,oracle-Ticker
, 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 interfaces constants with a qualified name, like this:
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 declaredStockWatcher.sunTickerabstract
. 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. TheStockApplet
implements theStockWatcher
interface, so the applet provides an implementation for thevalueChanged
method. The method ostensibly updates the applets display or otherwise uses this information.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.