Sub topic 2
Call Superclass Methods and Access Fields with super
A superclass is a class that another class builds on. The new class is its subclass. In Java, super lets a subclass use parts of its superclass.
A method is an action a class can perform. A field is a variable stored in an object. The example below uses super.speak() to call a superclass method and super.kind to read a superclass field.
Save this program as Main.java, then run javac Main.java and java Main.
class Animal {
String kind = "animal";
String name;
Animal(String name) {
this.name = name;
System.out.println("Animal constructor");
}
String speak() {
return name + " makes a sound";
}
}
class Dog extends Animal {
String kind = "dog";
Dog(String name) {
super(name);
System.out.println("Dog constructor");
}
@Override
String speak() {
return kind + " (" + super.kind + "): "
+ super.speak() + " and barks";
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Rex");
System.out.println(dog.speak());
}
}The output is:
Animal constructor
Dog constructor
dog (animal): Rex makes a sound and barksDog has its own kind field, which hides the field with the same name in Animal. In Dog, kind reads the dog field; super.kind reads the animal field. @Override tells Java to check that Dog.speak() replaces a superclass method.
A subclass cannot directly access a superclass field marked private, even with super.
Chain Constructors with super(...)
A constructor sets up an object when it is created. super(name) calls the Animal constructor and passes it the name "Rex". That constructor sets the animal’s name field.
When used, super(...) must be the first statement in the subclass constructor. If a constructor starts with neither super(...) nor this(...), Java inserts super(). This works only if the superclass has an accessible constructor with no arguments.
Follow Object Initialization Order
Initialization means giving fields their starting values. For new Dog("Rex"), Java follows this order:
- Give all object fields their default values, such as
nullfor aString. - Run the
Objectconstructor. - Initialize the
Animalfields, then run theAnimalconstructor body. - Initialize the
Dogfields, then run theDogconstructor body.
The superclass is therefore set up before the subclass constructor body runs.
Recognize Object as the Root Superclass
Object is Java’s root superclass: every class ultimately extends it. It provides methods such as toString(), which returns a text description of an object.
Exercise
In the example, what do super.kind and super(name) do?
Show answer
super.kind reads the Animal field. super(name) calls the Animal constructor with the given name.