Java Reference
In-Depth Information
structor, declaration and that initializes the fields of the object. It is ex-
ecuted 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 con-
structor with an equivalent initialization block:
class Body {
public long idNum;
public String name = "<unnamed>";
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 con-
structor.
This wasn't a particularly interesting use of an initialization block but it
did illustrate the syntax. In practice, initialization blocks are most use-
ful when you are writing anonymous inner classessee Section 5.4 on
page 144 that 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
 
Search WWH ::




Custom Search