THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

celestial body class Body:


import java.util.Iterator;


class AttributedBody extends Body
implements Attributed
{
private AttributedImpl attrImpl = new AttributedImpl();


public AttributedBody() {
super();
}


public AttributedBody(String name, Body orbits) {
super(name, orbits);
}


// Forward all Attributed methods to the attrImpl object


public void add(Attr newAttr)
{ attrImpl.add(newAttr); }
public Attr find(String name)
{ return attrImpl.find(name); }
public Attr remove(String name)
{ return attrImpl.remove(name); }
public Iterator attrs()
{ return attrImpl.attrs(); }
}


The declaration that AttributedBody extends Body and implements Attributed defines the contract
of AttributedBody. The implementations of all Body's methods are inherited from the Body class itself.
Each method of Attributed is implemented by forwarding the invocation to the AttributedImpl
object's equivalent method, returning its value (if any). This also means that you must add a field of type
AttributedImpl to use in the forwarding methods and initialize that field to refer to an
AttributedImpl object.


Forwarding is both straightforward and much less work than implementing Attributed from scratch.
Forwarding also enables you to quickly change the implementation you use, should a better implementation of
Attributed become available at some future date. However, forwarding must be set up manually and that
can be tedious and sometimes error prone.


4.5. Marker Interfaces


Some interfaces do not declare any methods but simply mark a class as having some general property. The
Cloneable interface is such a marker interfaceit has neither methods nor constants, but marks a class as
partaking in the cloning mechanism (see page 101).


Marker interfaces are the degenerate case of a contract because they define no language-level behaviorno
methods or values. All their contract is in the documentation that describes the expectations you must satisfy
if your class implements that interface. The interfaces Serializable and Externalizable (described
in "Object Serialization" on page 549) are marker interfaces, as are both java.rmi.Remote (see "java.rmi
Remote Method Invocation" on page 727) and java.util.EventListener (see "java.awt The Abstract
Window Toolkit" on page 717).


Marker interfaces can have a profound impact on the behavior of the classes that implement themconsider
Cloneable. Do not be fooled into thinking that they are unimportant merely because they have no methods.

Free download pdf