Java Reference
In-Depth Information
Implementing an Interface
Just as a class uses extends to specify its superclass, it can use implements to name
one or more interfaces it supports. implements is a Java keyword that can appear in
a class declaration following the extends clause. implements should be followed by
a comma-separated list of interfaces that the class implements.
When a class declares an interface in its implements clause, it is saying that it pro‐
vides an implementation (i.e., a body) for each mandatory method of that interface.
If a class implements an interface but does not provide an implementation for every
mandatory interface method, it inherits those unimplemented abstract methods
from the interface and must itself be declared abstract . If a class implements more
than one interface, it must implement every mandatory method of each interface it
implements (or be declared abstract ).
The following code shows how we can define a CenteredRectangle class that
extends the Rectangle class from Chapter 3 and implements our Centered
interface:
public class CenteredRectangle extends Rectangle implements Centered {
// New instance fields
private double cx , cy ;
// A constructor
public CenteredRectangle ( double cx , double cy , double w , double h ) {
super ( w , h );
this . cx = cx ;
this . cy = cy ;
}
// We inherit all the methods of Rectangle but must
// provide implementations of all the Centered methods.
public void setCenter ( double x , double y ) { cx = x ; cy = y ; }
public double getCenterX () { return cx ; }
public double getCenterY () { return cy ; }
}
Suppose we implement CenteredCircle and CenteredSquare just as we have
implemented this CenteredRectangle class. Each class extends Shape , so instances
of the classes can be treated as instances of the Shape class, as we saw earlier.
Because each class implements the Centered interface, instances can also be treated
as instances of that type. The following code demonstrates how objects can be
members of both a class type and an interface type:
Shape [] shapes = new Shape [ 3 ]; // Create an array to hold shapes
// Create some centered shapes, and store them in the Shape[]
// No cast necessary: these are all widening conversions
shapes [ 0 ] = new CenteredCircle ( 1.0 , 1.0 , 1.0 );
shapes [ 1 ] = new CenteredSquare ( 2.5 , 2 , 3 );
shapes [ 2 ] = new CenteredRectangle ( 2.3 , 4.5 , 3 , 4 );
Search WWH ::




Custom Search