super. You can also use super
to refer to a hidden field (although hiding fields is discouraged). Consider this class,
Superclass:
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
Subclass, that
overrides printMethod():
public class Subclass extends Superclass {
public void printMethod() { //overrides printMethod in Superclass
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
Subclass, the simple name
printMethod() refers to the one declared in
Subclass, which overrides the one in
Superclass. So, to refer to printMethod() inherited
from Superclass,
Subclass must use a qualified name, using
super as shown. Compiling and executing Subclass prints
the following:
Printed in Superclass. Printed in Subclass
super keyword
to invoke a superclass's constructor. Recall from the
Bicycle
example that
MountainBike is a subclass of
Bicycle. Here is the MountainBike (subclass) constructor that
calls the superclass constructor and then adds initialization code of its own:
public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}
The syntax for calling a superclass constructor is
super(); --or-- super(parameter list);
super(), the superclass no-argument constructor is called. With super(parameter list),
the superclass constructor with a matching parameter list is called.
Object does have such a constructor, so if
Object is the only superclass, there is no problem.
Object. In fact, this is the case. It is called
constructor chaining, and you need to be aware of it when there is a long line of class descent.