Java Reference
In-Depth Information
CHALLENGE 26.7
Which of the following objections are valid?
A. You can achieve the desired case effects by introducing similar operations in
a utility class.
B. One reason String is final is
to preserve immutability, and the
OoString class undermines this.
C. Classes such as StringReader cannot effectively be extended to work
with OoString objects instead of the String objects they expect.
D. To "extend" String , the OoString class should provide all the operations
that the String class provides.
E. Strings are built into the compiler in a special way that OoString cannot
emulate.
Summary
A major change that has accompanied the advent of object-oriented programming is that
programming is now a matter of extending an existing code base. Talented Java developers
spend more time reading than writing, to understand how their code will fit with and benefit
from the voluminous class libraries. One class that you should be especially sure to
understand is Object , the superclass from which all your classes will derive.
The subclasses you create should be logical and consistent extensions of their superclasses.
The Java compiler will enforce some aspects of consistency; in many areas, however,
consistency is a matter of judgment. The Liskov Substitution Principle suggests that subtypes
should uphold the behavior of supertypes. A good policy is to violate this principle only when
you have a compelling justification.
In addition to subclassing, you can extend through delegation. This is more fragile than
subclassing but may be necessary if your class needs to provide the behavior of multiple
superclasses.
A healthy view is that development is a matter of extending the Java code base with just the
changes you need for your application. Aggressive reuse of the Java class libraries will you
help you reduce the chances for introducing defects and will let you benefit from the hard
work of many developers who have preceded you. With a good understanding of the existing
code base, you can develop rich applications as minimal extensions of existing code.
Beyond Ordinary Extension
The ordinary way to extend a software system is to find a suitable superclass—usually
Object —and to subclass it. You can also "inherit" behavior from more than one class by
copying some of the operations of a second class and delegating calls to an instance of that
class. Both of these extension techniques, however, require that you know at compile time
what behaviors you want to add. If you need to add behavior to an object without changing its
Search WWH ::




Custom Search