Java Reference
In-Depth Information
The syntax to call a superclass's constructor is:
super (), or super (parameters);
The statement super() invokes the no-arg constructor of its superclass, and the statement
super(arguments) invokes the superclass constructor that matches the arguments . The
statement super() or super(arguments) must appear in the first line of the subclass's
constructor; this is the only way to explicitly invoke a superclass constructor. For example, the
constructor in lines 12-17 in Listing 11.2 can be replaced by the following code:
public CircleFromSimpleGeometricObject(
double radius, String color, boolean filled) {
super (color, filled);
this .radius = radius;
}
Caution
You must use the keyword super to call the superclass constructor, and the call must
be the first statement in the constructor. Invoking a superclass constructor's name in a
subclass causes a syntax error.
11.3.2 Constructor Chaining
A constructor may invoke an overloaded constructor or its superclass constructor. If neither is
invoked explicitly, the compiler automatically puts super() as the first statement in the con-
structor. For example:
public ClassName() {
// some statements
public ClassName() {
super ();
Equivalent
// some statements
}
}
public ClassName( double d) {
// some statements
public ClassName( double d) {
super ();
Equivalent
// some statements
}
}
In any case, constructing an instance of a class invokes the constructors of all the superclasses
along the inheritance chain. When constructing an object of a subclass, the subclass construc-
tor first invokes its superclass constructor before performing its own tasks. If the superclass is
derived from another class, the superclass constructor invokes its parent-class constructor
before performing its own tasks. This process continues until the last constructor along the
inheritance hierarchy is called. This is called constructor chaining .
Consider the following code:
constructor chaining
1 public class
Faculty extends Employee
{
2
public static void main(String[] args) {
3
4 }
5
6
new Faculty();
public Faculty()
{
 
Search WWH ::




Custom Search