Java Reference
In-Depth Information
figure 4.17
The Rectangle class
(abbreviated), which
implements the
Stretchable interface
1 public class Rectangle extends Shape implements Stretchable
2 {
3 /* Remainder of class unchanged from Figure 4.12 */
4
5 public void stretch( double factor )
6 {
7 if( factor <= 0 )
8 throw new IllegalArgumentException( );
9
10 if( length > width )
11 length *= factor;
12 else
13 width *= factor;
14 }
15 }
4.4.2 implementing an interface
A class implements an interface by
The implements
clause is used to
declare that a class
implements an
interface. The class
must implement all
interface methods
or it remains
abstract.
1.
Declaring that it implements the interface
2.
Defining implementations for all the interface methods
An example is shown in Figure 4.17. Here, we complete the Rectangle
class, which we used in Section 4.2.
Line 1 shows that when implementing an interface, we use implements
instead of extends . We can provide any methods that we want, but we must
provide at least those listed in the interface. The interface is implemented at
lines 5 to 14. Notice that we must implement the exact method specified in the
interface.
A class that implements an interface can be extended if it is not final. The
extended class automatically implements the interface.
As we see from our example, a class that implements an interface may still
extend one other class. The extends clause must precede the implements clause.
4.4.3 multiple interfaces
As we mentioned earlier, a class may implement multiple interfaces. The
syntax for doing so is simple. A class implements multiple interfaces by
1.
Listing the interfaces (comma separated) that it implements
2.
Defining implementations for all of the interface methods
The interface is the ultimate in abstract classes and represents an elegant
solution to the multiple inheritance problem.
 
Search WWH ::




Custom Search