Java Reference
In-Depth Information
If the list's method were a void method, we could give the overriding version an empty
body, but then the client would be unaware that the method did not do anything.
•
Implement the list's
add
and
replace
methods within the class
SortedList
and have them
throw an exception when invoked. For example,
add
could appear as follows:
public boolean
add(
int
newPosition, T newEntry)
{
throw new
UnsupportedOperationException("Illegal attempt to add " +
"at a specified position within a sorted list.");
}
// end add
This version of
add
also overrides the version that
LList
implements. If the client invokes
this method, an exception occurs. This approach is a common practice, and it is the one we
prefer.
Note:
If
SortedList
overrides the list's method
add
, the class's implementation still can
invoke the method, as happens in Segment 17.1. The use of
super
in the call indicates that we
are invoking the list's version of the method, not the overriding version in
SortedList
.
Question 2
As a variation of the second possibility just given, you could implement the ADT
list's two
add
methods within
SortedList
so that each one calls the
add
method specified in
SortedListInterface
. In this way, the new entry is added in its correct position within the
sorted list. Why is this not a good idea?
Programming Tip:
If your class inherits methods that are inappropriate, you can over-
ride them with methods that throw an exception when invoked. In such a case, examine your
design and consider whether inheritance was the right choice. Do the benefits of inheritance
outweigh the inconvenience of overriding the inappropriate methods, or would composition
provide a cleaner design?
17.4
Efficiency.
The implementation of
SortedList
given here has the same efficiency—or inefficiency
in this case—as the version that uses composition given in the previous chapter. If
LList
had been
designed with inheritance in mind,
SortedList
could access
LList
's underlying data structure and
provide faster operations. To this end, we revise the class
LList
in the next section.
Note:
The implementation of the sorted list that extends the class
LList
is as inefficient as
the implementation that uses composition given in the previous chapter.
Question 3
Give at least one advantage and one disadvantage of using inheritance in the
way shown in this section to implement the class
SortedList
.
17.5
Let's examine the class
LList
that we developed in Chapter 14 as a linked implementation of the
ADT list. Recall that the class places each of the list's entries into its own node. These nodes are
linked so that the first entry's node references the node of the second entry, and so on. A data field
firstNode
of the class references the first node, and another data field
numberOfEntries
counts the
number of entries in the list.