Java Reference
In-Depth Information
followed by parentheses, it refers to the constructor of the superclass. If superclass constructor accepts parameters,
you can pass a list of parameters within parentheses similar to a method call. The following are examples of calling
constructor of a superclass:
// Call no-args constructor of superclass
super();
// Call superclass constructor with a String argument
super("Hello");
// Call superclass constructor with two double arguments
super(10.5, 89.2);
You can call constructor of the superclass explicitly or let the compiler inject the call to the no-args constructor
for you. When you compile the
CSuper
and
CSub
class, the compiler modifies their constructors' code, which looks as
shown in Listing 16-21 and Listing 16-22.
Listing 16-21.
Compiler Injection of a super() Call to Call the Immediate Ancestor's no-args Constructor
// CSuper.java
package com.jdojo.inheritance;
public class CSuper {
public CSuper() {
super(); // Injected by the compiler
System.out.println("Inside CSuper() constructor.");
}
}
Listing 16-22.
Compiler Injection of a super() Call to Call the Immediate Ancestor's no-args Constructor
// CSub.java
package com.jdojo.inheritance;
public class CSub extends CSuper {
public CSub() {
super(); // Injected by the compiler
System.out.println("Inside CSub() constructor.");
}
}
■
the keyword
super
refers to the immediate ancestor of a class. You can call superclass constructors using the
super
keyword only as the first statement inside a constructor.
Tip
You can also call the no-args constructor or any other constructors of the superclass explicitly as the first
statement inside constructors of your class. The compiler injects the no-args constructor call only if you have not
added one explicitly. Let's try to improve your
Employee
and
Manager
classes. Let's add a constructor to the
Employee
class that accepts the name of the employee as a parameter. You will call the new class
Employee2
, as shown in
Listing 16-23.