Java Reference
In-Depth Information
PITFALL: (continued)
The optional methods are not, strictly speaking, optional. Like the other methods
in an interface, the optional methods must have a method body so that the optional
method heading is converted to a complete method defi nition. So, what is option-
al? The “optional” refers to the semantics of the method. If the method is optional,
then you may give it a trivial implementation and you will not have shirked your
responsibility to follow the (unenforced) semantics for the interface.
To keep these optional methods from producing unexplained failures, the interface
semantics say that if you do not give an optional method a “real” implementation,
then you should have the method body throw an UnsupportedOperationExcep-
tion . For example, the add method of the Collection<T> interface is optional and
so can be implemented as follows (provided you have good reason for this):
public boolean add(T element)
{
throw new UnsupportedOperationException();
}
The UnsupportedOperationException class is a derived class of the RunTimeExcep-
tion class, so an UnsupportedOperationException is an unchecked exception,
meaning it need not be caught in a catch block or declared in a throws clause.
The intention is that the code for a class that implements an interface with optional
methods would be written and used in such a way that this UnsupportedOperation
Exception would only be thrown during debugging. These rules on optional meth-
ods are part of the semantics of the interface, and like all other parts of the semantics of
an interface, they depend entirely on the good will and responsibility of the program-
mer defi ning the class that implements the interface.
Optional Methods
When an interface lists a method as “optional,” you still need to implement it when defining a
class that implements the interface. However, if you do not want to give it a “real” definition,
you can simply have the method body throw an UnsupportedOperationException .
TIP: Dealing with All Those Exceptions
If you examine the Collection<T> , Set<T> , and List<T> interfaces in Appendix 5 ,
you will see that many of the methods are liberally sprinkled with statements that
certain exceptions are thrown. All these exception classes are unchecked exceptions,
meaning that they need not be caught in a catch block and need not be declared in
a throws clause. They are there primarily for debugging. If you are using an existing
(continued)
 
Search WWH ::




Custom Search