Java Reference
In-Depth Information
Circle original = new Circle ( 1 , 2 , 3 ); // regular constructor
Circle copy = new Circle ( original ); // copy constructor
It can be difficult to implement clone() correctly, and it is usually easier and safer
to provide a copy constructor. To make the Circle class cloneable, you would add
Cloneable to the implements clause and add the following method to the class
body:
@Override public Object clone () {
try { return super . clone (); }
catch ( CloneNotSupportedException e ) { throw new AssertionError ( e ); }
}
Aspects of Object-Oriented Design
In this section, we will consider several techniques relevant to object-oriented
design in Java. This is a very incomplete treatment and merely intended to showcase
some examples—the reader is encouraged to consult additional resources, such as
the aforementioned Efective Java by Joshua Bloch.
We start by considering good practices for defining constants in Java, before moving
on to discuss different approaches to using Java's object-oriented capabilities for
modeling and domain object design. At the end of the section, we conclude by cov‐
ering the implementation of some common design patterns in Java.
O n
Constants
As noted earlier, constants can appear in an interface definition. Any class that
implements an interface inherits the constants it defines and can use them as if they
were defined directly in the class itself. Importantly, there is no need to prefix the
constants with the name of the interface or provide any kind of implementation of
the constants.
When a set of constants is used by more than one class, it is tempting to define the
constants once in an interface and then have any classes that require the constants
implement the interface. This situation might arise, for example, when client and
server classes implement a network protocol whose details (such as the port number
to connect to and listen on) are captured in a set of symbolic constants. As a con‐
crete example, consider the java.io.ObjectStreamConstants interface, which
defines constants for the object serialization protocol and is implemented by both
ObjectInputStream and ObjectOutputStream .
The primary benefit of inheriting constant definitions from an interface is that it
saves typing: you don't need to specify the type that defines the constants. Despite
its use with ObjectStreamConstants , this is not a recommended technique. The use
of constants is an implementation detail that is not appropriate to declare in the
implements clause of a class signature.
A better approach is to define constants in a class and use the constants by typing
the full class name and the constant name. You can save typing by importing the
Search WWH ::




Custom Search