Accessing Superclass Members
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword
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.");
}
}
Here is a subclass, called
Subclass, that overrides printMethod():public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
Within
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
Subclass Constructors
The following example illustrates how to use thesuperkeyword to invoke a superclass's constructor. Recall from theBicycleexample thatMountainBikeis a subclass ofBicycle. Here is theMountainBike(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; }Invocation of a superclass constructor must be the first line in the subclass constructor.The syntax for calling a superclass constructor isor:super();
super(parameter list);Withsuper(), the superclass no-argument constructor is called. Withsuper(parameter list), the superclass constructor with a matching parameter list is called.
No comments:
Post a Comment