Java Reference
In-Depth Information
working against the interface will just begin to use the new implementation without
needing to know.
Note In some cases, alterations of existing classes can cause code to break. This is
more often the case when working with libraries. For instance, suppose a class imple-
ments an interface that is updated with a new method signature. All classes that imple-
ment that interface must now be updated to include an implementation of the new meth-
od, which is sometimes impossible within library classes in order to maintain backward
compatibility. This is the main reason for the inclusion of default methods in Java 8; see
Recipe 5-7 for more details.
Finally, interfaces help to promote security. They hide implementation details of
methods that are declared in an interface from any class that may call that method us-
ing the interface. As mentioned in the previous paragraph, if a class is calling the
getFullName() method against the TeamType interface, it does not need to know
the implementation details of that method as long as the result is returned as expected.
The Enterprise JavaBean (EJB) 3.0 model used interfaces for interacting with
methods that performed database work. This model worked very well for hiding the de-
tails and logic that were not essential for use from other classes. Other frameworks use
similar models, exposing functionality through Java interfaces. Interface use has
proven to be a smart way to code software because it promotes reusability, flexibility,
and security.
5-10. Making a Class Cloneable
Problem
You would like to enable a class to be cloned by another class.
Solution
Implement the Cloneable interface within the class that you want to clone; then call
that object's clone method to make a copy of it. The following code demonstrates how
to make the Team class cloneable:
Search WWH ::




Custom Search