THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

extenders of the class. Both of these contracts must be carefully designed.


With class extension, inheritance of contract and inheritance of implementation always occur together.
However, you can define new types independent of implementation by using interfaces. You can also reuse
existing implementations, without affecting type, by manually using composition and forwarding. Interfaces
and composition are discussed in Chapter 4.


Class extension that involves generic classes has its own special rules concerning redefining members,
overriding, and overloading. These rules are discussed in detail in Chapter 11. In this chapter, generic types
are not considered.


3.1. An Extended Class


To demonstrate subclassing, we start with a basic attribute class designed to store namevalue pairs. Attribute
names are human-readable strings, such as "color" or "location." Attribute values are determined by the kind
of attribute; for example, a "location" may have a string value representing a street address, or it may be a set
of integer values representing latitude and longitude.


public class Attr {
private final String name;
private Object value = null;


public Attr(String name) {
this.name = name;
}


public Attr(String name, Object value) {
this.name = name;
this.value = value;
}


public String getName() {
return name;
}


public Object getValue() {
return value;
}


public Object setValue(Object newValue) {
Object oldVal = value;
value = newValue;
return oldVal;
}


public String toString() {
return name + "='" + value + "'";
}
}


An attribute must have a name, so each Attr constructor requires a name parameter. The name must be
immutable (and so is marked final) because it may be used, for example, as a key into a hashtable or sorted
list. In such a case, if the name field were modified, the attribute object would become "lost" because it would
be filed under the old name, not the modified one. Attributes can have any type of value, so the value is stored
in a variable of type Object. The value can be changed at any time. Both name and value are private
members so that they can be accessed only via the appropriate methods. This ensures that the contract of
Attr is always honored and allows the designer of Attr the freedom to change implementation details in

Free download pdf