Java Reference
In-Depth Information
If we know that the Rectangle class has a stretch method, then it is proba-
bly not a good design to have Square extend Rectangle . If Square already
extends Rectangle and then later on we want to add stretch to Rectangle , there
are two basic ways to proceed.
Option #1 would be to have Square override stretch with an implementa-
tion that throws an exception:
public void stretch( double factor )
{ throw new UnsupportedOperationException( ); }
With this design, at least squares will never lose their squareness.
Option #2 would be to redesign the entire hierarchy to have Square no
longer extend Rectangle . This is known as refactoring . Depending on how
complicated the entire hierarchy is, this could be an incredibly messy task.
However, some development tools can automate much of the process. The best
plan, especially for a large hierarchy is to think about these issues at the time
of design, and ask what the hierarchy might reasonably look like in the future.
Often this is easy to say, but very challenging to do.
A similar philosophy occurs when deciding what exceptions should be
listed in the throws list of a method. Because of the IS-A relationship, when a
method is overridden, new checked exceptions cannot be added to the throws
list. The overriding implementation can reduce, or subset, the original list of
checked exceptions, but can never add to it. As such, in determining the
throws list of a method, the designer should look not only at the exceptions
that can be thrown in the current implementation of the method, but also what
exceptions might reasonably be thrown by the method in the future (should
the implementation change) and what exceptions might be thrown by overrid-
ing implementations provided by future subclasses.
multiple inheritance
4.3
All the inheritance examples seen so far derived one class from a single base
class. In multiple inheritance , a class may be derived from more than one base
class. For instance, we may have a Student class and an Employee class. A
StudentEmployee could then be derived from both classes.
Although multiple inheritance sounds attractive, and some languages
(including C++) support it, it is wrought with subtleties that make design
difficult. For instance, the two base classes may contain two methods that
have the same signature but different implementations. Alternatively, they
may have two identically named fields. Which one should be used?
Multiple inheritance
is used to derive a
class from several
base classes. Java
does not allow mul-
tiple inheritance.
 
 
Search WWH ::




Custom Search