Java Reference
In-Depth Information
Chapter 14. Introducing Construction
When you create a Java class, you normally provide for the creation of objects of your class
by supplying class constructors. In many regards, constructors are like any other methods, but
Java has numerous rules that specifically govern the use of constructors. In particular,
constructors have special abilities to collaborate with one another.
Ordinary Construction
Java constructors are special methods. In many respects, including visibility modifiers and
exception handling, constructors are like ordinary methods. On the other hand, a significant
number of syntactic and semantic rules govern the use and behavior of constructors. These
extra rules emerge because classes are significantly different from other objects in Java. In
Smalltalk, by comparison, classes are objects that are responsible for providing constructors.
There is no special syntax for constructors, a simplification that helps keep Smalltalk syntax
small.
CHALLENGE 14.1
List three or four rules that govern the use and behavior of constructors in Java.
Smalltalk's simple syntax for constructors is not proof per se of Smalltalk's superiority. In
fact, Smalltalk's organization of the class of a class of a class is mind-numbingly difficult to
comprehend for most developers. The point of comparing Java to other languages is not to
determine superiority but rather for us to deepen our understanding of the design choices built
into Java and how they affect us as developers. One aspect of Java constructors that is
important to understand is the collaboration that you can orchestrate among constructors.
Superclass Collaboration
Eventually, a constructor always collaborates with one of its superclass's constructors. If
a class has no declared constructor, Java supplies a default one equivalent to a constructor
with no arguments and no statements. If the first statement in a constructor is anything other
than a specific invocation of another constructor, Java inserts a call to super() ,
thesuperclass's constructor with no arguments. This causes a compilation error if
the superclass does not provide a constructor with no arguments.
In Figure 14.1, for example the classes capture the idea that a fountain is one type of firework.
(A fountain is a ground-based firework that emits a spray of sparks.) Suppose that at an early
stage of development, we have no constructors defined. In this case, Java supplies a default
constructor—one that accepts no arguments—for both classes. It is legal to instantiate these
objects with such lines as:
Fountain f = new Fountain();
Search WWH ::




Custom Search