Java Reference
In-Depth Information
the constructor in class Test2 takes three parameters. Which constructor in
the superclass should be invoked? It is unwise to leave it to the compiler to
“guess.” (Actually, the compiler does not guess; it follows specific rules, which
we discuss later.) Let's suppose that our design requires that the two-argument
constructor in Test1 be called. Therefore, the Test2 constructor invokes the
second constructor in class Test1 by using super(a, b) . Had we wanted the
one-argument constructor, we would use super (a) or super (b) .
class Test1 {
int i;
int j;
Test1(int i)
{this.i = i;}
Test1 (int i, int j) {
this.i = i;
this.j = j;
}
}
class Test2 extends Test1 {
float x;
Test2 (int a, int b, float c) {
super (a, b); // Must be first statement
x = c;
}
}
As with this() , the parameter list identifies which of the overloaded construc-
tors in the superclass to invoke. And as with this() , the super() invocation
must occur as the first statement of the constructor and cannot appear in regular
methods.
Do not confuse the this and super references with the this() and
super() constructor operators. The this and super references are used to
gain access to data and methods in a class and superclass, respectively, while the
this() and super() constructor operators indicate which constructors in the
class and superclass to invoke.
4.3.3 Construction sequence
When you instantiate a subclass, the object construction begins with an invo-
cation of the constructor in the topmost base class and initializes downward
 
Search WWH ::




Custom Search