Java Reference
In-Depth Information
4.4. Working with Interfaces
The previous chapter introduced the Attr class and showed how to extend
it to make specialized types of attribute objects. Now all you need is the
ability to associate attributes with objects.
The first decision to make is whether having attributes is reflected in the
type of the object. An object could, if you chose, contain a set of attrib-
utes and allow programmers access to that set. Or you could say that be-
ing able to store attributes on an object is a part of its type and so should
be part of the type hierarchy. Both positions are legitimate. We believe
that representing the ability to hold attributes in the type hierarchy is
most useful. We will create an Attributed type to be used for objects that
can be attributed by attaching Attr objects to them.
To create an Attributed type you could define a class that would form the
superclass for all attributed objects. But then programmers must decide
whether to inherit from Attributed or from some other useful class. In-
stead we make Attributed into an interface:
public interface Attributed {
void add(Attr newAttr);
Attr find(String attrName);
Attr remove(String attrName);
java.util.Iterator<Attr> attrs();
}
This interface declares four methods: one for adding a new attribute to
an Attributed object; one for finding whether an attribute of a given name
has been added to that object; one for removing an attribute from an
object; and one for accessing all of the attributes currently attached to
the object.
When we add an attribute to an object, that object considers itself the
owner of that Attr instance until it is removed. If the attribute has its
value changed or is shared among a number of objects, then the expect-
 
Search WWH ::




Custom Search