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 Chapter
12.
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 constructor,
declaration and that initializes the fields of the object. It is executed as if it were placed at the beginning of
every constructor in the classwith multiple blocks being executed in the order they appear in the class. An
initialization block can throw a checked exception only if all of the class's constructors are declared to throw
that exception.
For illustration, this variant of the Body class replaces the no-arg constructor with an equivalent initialization
block:
class Body {
public long idNum;
public String name = "
public Body orbits = null;
private static long nextID = 0;
{
idNum = nextID++;
}
public Body(String bodyName, Body orbitsAround) {
name = bodyName;
orbits = orbitsAround;
}
}
Now the two-argument constructor doesn't need to perform the explicit invocation of the no-arg constructor,
but we no longer have a no-arg constructor and so everyone is forced to use the two-argument constructor.
This wasn't a particularly interesting use of an initialization block but it did illustrate the syntax. In practice,
initialization blocks are most useful when you are writing anonymous inner classessee Section 5.4 on page
144that can't have constructors. An initialization block can also be useful to define a common piece of code
that all constructors execute. While this could be done by defining a special initialization method, say init,
the difference is that such a method would not be recognized as construction code and could not, for example,
assign values to blank final fields. Initialization is the purpose of having initialization blocks, but in practice
you can make it do anythingthe compiler won't check what it does. Spreading initialization code all through a
class is not a good design, and initialization blocks should be used judiciously, when they express something
that cannot easily be done by constructors alone.