Java Reference
In-Depth Information
through the constructors in each subclass until it reaches the final subclass
constructor. The question then arises: if one or more of the superclasses have
multiple constructors, which constructor does the JVM invoke? The answer
is that, unless told otherwise with super() , the JVM will always choose the
zero-argument constructor.
Let's begin with the simplest case of a superclass definition without any con-
structors. In this case, as we learned in Chapter 3, the compiler automatically
generates a zero-argument constructor that does nothing. Almost as simple is
the case of a superclass with an explicit zero-argument constructor and no other
constructors. In both of these cases, the subclass constructor does not need to
explicitly invoke super() because the JVM automatically invokes the zero-
argument constructor in the superclass - either the zero-argument constructor
provided in the superclass source code if there is one, or the default do-nothing
“free” constructor if no explicit constructor is provided.
If the superclass contains one or more explicit constructors, then the compiler
does not generate a free zero-argument constructor. A subclass that does not
utilize super() to choose one of the existing constructors fails to compile since
there is no zero-argument superclass constructor to use. Therefore, the subclass
must employ a super() with a parameter list matching one of the superclass
constructors.
If the subclass also holds several constructors, each must invoke a super() to
one of the superclass constructors (or perhaps use this() to refer to a subclass
constructor that does use super() ). The compiler and JVM figure out the proper
sequence of constructors to call as the subclass instance is being built according
to which constructor is used with the new operator.
The example code here shows two different sequences of constructors
invoked for the case of a base class and two subclasses, all with overloaded
constructors:
public class ConstructApp3 {
public static void main (String[] args) {
// Create two instances of Test2
// using two different constructors.
System.out.println ("First test2 object");
Test2 test2 = new Test2 (1.2, 1.3);
System.out.println (" \ nSecond test2 object");
test2 = new Test2 (true, 1.2, 1.3);
}
}
 
Search WWH ::




Custom Search