Java Reference
In-Depth Information
The first line is an array's representation of itself. The second line is a list's self-
representation. The remaining output reflects an unhandled exception that occurs because the
add() method throws an UnsupportedOperationException . The implementation of
List that asList() returns does not support adding values to the list. You can work around
this limitation by defining the list as follows:
List L = new ArrayList(Arrays.asList(names));
CHALLENGE 26.5
Does Arrays.asList() violate LSP? Can you justify why this method returns an
implementation of List that does not support the full List interface?
Extending by Delegating
Extension through delegation occurs when a class has methods that forward calls to identical
operations supplied by another object. This technique makes available the behavior of the
forwarded-to class on the class you are extending, but this is usually not the best way to
achieve extension. If you want to inherit the exact methods of an existing class, the most
straightforward approach is to subclass it. However, this is not always possible. The class
whose behavior you need may be declared final —as String is, for example—or your
class may already be subclassing something else. In these cases, you can extend your class
through delegation.
CHALLENGE 26.6
Suppose that you want to make a class in an existing hierarchy observable, so that
interested clients can register for notification of changes. Name an existing class
from which you can "inherit" these features, and describe how the delegation works.
Extending a final class using delegation is usually questionable, or just a plain bad idea.
Suppose that a colleague asks for your thoughts about extending the String class with an
OoString class that adds a few new behaviors. Specifically, he wants Oozinoz strings to
provide setTitle-Case() and setRandomCase() methods. ( Title case means that
characters after whitespace are in uppercase. Random case means that characters in the string
are uppercase or lowercase at random.) Figure 26.6 shows the proposed OoString class,
which adds functions that change the case of text, such as ad copy for a Web site:
package com.oozinoz.dubious;
public class ShowOoString
{
public static void main(String args[])
{
OoString os =
new OoString(
"Launch our newest rocket "
+ "from any international waters!");
Search WWH ::




Custom Search