Java Reference
In-Depth Information
Whether this is correct depends on the contract of the class and on what
the uniqueness of
idNum
is supposed to indicatefor this example we won't
concern ourselves with that.
This idiom is not used much within the Java class libraries, because the
preferred way to make a direct copy of an object is by using the
clone
methodsee "
Cloning Objects
"
on page
101
.
However, many classes sup-
port a more general form of construction that "copies" another object.
For example, the
StringBuilder
and
StringBuffer
classes (described in
Chapter 13
)
each have a constructor that takes a single
CharSequence
argument that allows you to copy an existing
String
,
StringBuffer
, or
StringBuilder
object; and the collection classes (described in
Chapter
ment and so allow one collection to be initialized with the same contents
as another (which need not be of exactly the same type). Writing a cor-
rect copy constructor requires the same consideration as writing a cor-
rect
clone
method.
Constructors can also be declared to throw checked exceptions. The
tHRows
clause comes after the parameter list and before the opening
curly brace of the constructor body. If a
tHRows
clause exists then
any method that invokes this constructor as part of a
new
expression
must either catch the declared exception or itself declare that it throws
that exception. Exceptions and
throws
clauses are discussed in detail in
Exercise 2.7
: Add two constructors to
Vehicle
: a no-arg constructor
and one that takes an initial owner's name. Modify the
main
program so
that it generates the same output it did before.
Exercise 2.8
: What constructors should you add to
LinkedList
?
2.5.2. Initialization Blocks
Another way to perform more complex initialization of fields is to use an
initialization block.
An initialization block is a block of statements that
appears within the class declaration, outside of any member, or con-