Java Reference
In-Depth Information
inherited fields of the class. To invoke the superclass constructor, our constructor
calls super() .
super is a reserved word in Java. One of its uses is to invoke the constructor of a
superclass from within a subclass constructor. This use is analogous to the use of
this() to invoke one constructor of a class from within another constructor of the
same class. Invoking a constructor using super() is subject to the same restrictions
as is using this() :
super() can be used in this way only within a constructor.
• The call to the superclass constructor must appear as the first statement within
the constructor, even before local variable declarations.
The arguments passed to super() must match the parameters of the superclass con‐
structor. If the superclass defines more than one constructor, super() can be used
to invoke any one of them, depending on the arguments passed.
Constructor Chaining and the Default Constructor
Java guarantees that the constructor of a class is called whenever an instance of that
class is created. It also guarantees that the constructor is called whenever an instance
of any subclass is created. In order to guarantee this second point, Java must ensure
that every constructor calls its superclass constructor.
Thus, if the first statement in a constructor does not explicitly invoke another con‐
structor with this() or super() , the javac compiler inserts the call super() (i.e., it
calls the superclass constructor with no arguments). If the superclass does not have
a visible constructor that takes no arguments, this implicit invocation causes a com‐
pilation error.
Consider what happens when we create a new instance of the PlaneCircle class.
• First, the PlaneCircle constructor is invoked.
• This constructor explicitly calls super(r) to invoke a Circle constructor.
• That Circle() constructor implicitly calls super() to invoke the constructor of
its superclass, Object ( Object only has one constructor).
• At this point, we've reached the top of the hierarchy and constructors start to
• The body of the Object constructor runs first.
• When it returns, the body of the Circle() constructor runs.
• Finally, when the call to super(r) returns, the remaining statements of the Pla
neCircle() constructor are executed.
What all this means is that constructor calls are chained; any time an object is cre‐
ated, a sequence of constructors is invoked, from subclass to superclass on up to
Search WWH ::

Custom Search