Sub topic 5
Call Superclass Methods and Access Fields with super
Why you need super
A subclass can replace a method it inherits. This is called overriding. Sometimes you do not want to throw the old behavior away. You want to add to it. The super keyword lets a subclass reach the superclass version of a method or field.
In this chapter you will learn what super is, how to call an overridden method with it, how it works with fields, and where it cannot be used. We assume you know classes, objects, fields, methods, and constructors, and that you have seen extends and method overriding.
Some terms first:
- A superclass is the class you inherit from. It is also called the parent class.
- A subclass is the class that uses
extends. It is also called the child class. - Overriding means a subclass provides its own version of an inherited instance method, with the same name and parameters.
- A keyword is a word with a fixed meaning in the language. You cannot use it as a variable name.
What super means
Inside an instance method, this is a reference to the current object. The keyword super also refers to the current object, but it treats that object as an instance of its superclass. That means super.something looks for something starting in the superclass, not in the current class.
There are three ways to use super:
| Form | Meaning |
|---|---|
| `super.method(args)` | Call the superclass version of a method |
| `super.field` | Read or write a field declared in the superclass |
| `super(args)` | Call a superclass constructor (covered in the next chapter) |
This chapter covers the first two forms.
Calling an overridden method
Look at this program.
class Animal {
private final String name;
Animal(String name) {
this.name = name;
}
String speak() {
return name + " makes a sound";
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
@Override
String speak() {
return super.speak() + " and barks";
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog("Rex");
System.out.println(animal.speak());
}
}The output is:
Rex makes a sound and barksHere is what happens step by step:
animal.speak()runs theDogversion, because the object is really aDog.- Inside
Dog.speak(), the callsuper.speak()runs theAnimalversion. - The
Animalversion returns"Rex makes a sound". Dogadds" and barks"and returns the longer text.
Without super., the call speak() inside Dog.speak() would call itself. That would repeat forever and end with a StackOverflowError. The super. prefix is what sends the call up one level.
Extend behavior instead of replacing it
Using super.method() is a common pattern. The subclass reuses the work of the parent and adds its own step. Here is a second example.
class Account {
protected double balance;
void deposit(double amount) {
balance += amount;
System.out.println("Deposited " + amount);
}
}
class LoggedAccount extends Account {
@Override
void deposit(double amount) {
System.out.println("Starting deposit...");
super.deposit(amount);
System.out.println("Balance is now " + balance);
}
}
public class AccountDemo {
public static void main(String[] args) {
LoggedAccount account = new LoggedAccount();
account.deposit(50.0);
}
}The output is:
Starting deposit...
Deposited 50.0
Balance is now 50.0The subclass does not copy the logic that updates the balance. If the parent changes how deposits work, the subclass gets the change automatically.
You can call super.method() at any point. You can call it first, last, in the middle, or only under some condition. You can also skip it. If you skip it, the parent's logic does not run at all. Sometimes that is what you want. Often it is a bug, so check what the parent method does before you decide.
Accessing fields with super
A subclass can declare a field with the same name as a field in its superclass. This is called field hiding. The two fields both exist in the object. They are separate variables that happen to share a name.
Inside the subclass, the plain name refers to the subclass field. Use super.name to reach the superclass one.
class Vehicle {
String type = "vehicle";
}
class Car extends Vehicle {
String type = "car";
void show() {
System.out.println(type);
System.out.println(this.type);
System.out.println(super.type);
}
}
public class FieldDemo {
public static void main(String[] args) {
new Car().show();
}
}The output is:
car
car
vehicleHiding fields is usually a bad idea. It confuses readers, and fields do not behave like methods. Fields are not overridden. Java picks the field from the declared type of the variable, not from the real object. Compare these lines:
Vehicle v = new Car();
System.out.println(v.type); // prints "vehicle"
System.out.println(((Car) v).type); // prints "car"A method call would use the real object (Car), but a field access uses the variable's type (Vehicle). Avoid this trap by giving fields different names in the subclass.
The more common case is a field with no hiding at all. If the superclass has a field and the subclass does not redeclare it, you can use the plain name, or this.name, or super.name. They all refer to the same variable. In the LoggedAccount example, balance is protected, so balance, this.balance, and super.balance would all work and mean the same thing.
Access rules still apply
super does not bypass access modifiers. It only chooses where the search starts. You can use super.x only if the subclass is allowed to see x.
- A
privatemember of the superclass cannot be reached, even withsuper. The compiler reports an error. - A package-private member (no modifier) is visible only if the subclass is in the same package.
- A
protectedorpublicmember is visible to the subclass.
In the first example, name is private in Animal. Dog cannot write super.name. This is why Dog.speak() calls super.speak() instead of reading the name directly. The parent exposes behavior, and the child uses it.
What super cannot do
Only one level up
super goes to the direct superclass. You cannot chain it like super.super.speak(). That is a compile error.
Suppose Puppy extends Dog extends Animal. Inside Puppy, super.speak() calls Dog.speak(). If Dog.speak() itself uses super.speak(), then Animal.speak() runs too. The chain works because each class calls the next one, not because one class skips levels.
Not in static methods
A static method belongs to the class, not to an object. There is no current object, so there is no super. This code does not compile:
class Child extends Parent {
static void test() {
super.hello(); // compile error
}
}The same rule applies to this. To call a static method of the superclass, use the class name, such as Parent.hello().
Not for fully abstract calls
If a superclass method is abstract, it has no body. Calling it with super.method() is a compile error because there is nothing to run. This matters when you work with abstract classes, which come later in this tutorial.
Not a way to undo dynamic dispatch from outside
Only code inside the subclass can write super.method(). Code outside cannot say "call the Animal version on this Dog". Once an object is a Dog, other code always gets the Dog behavior. The subclass controls when the parent version runs.
super and this compared
Both keywords refer to the current object. They differ in where the search for a name begins.
| Expression | Where Java starts looking |
|---|---|
| `this.speak()` | In the current class, then up the parent chain at runtime |
| `speak()` | Same as `this.speak()` |
| `super.speak()` | In the direct superclass, then up its parent chain |
A call with super. is not dispatched to a later override. In Dog.speak(), super.speak() always runs Animal's version, even if a class below Dog overrides speak() again. A plain this.speak() would run the most specific override.
Common mistakes
- Forgetting
super.and calling the method recursively.speak()insidespeak()calls itself and overflows the stack. - Skipping the parent call by accident. The override compiles, but the parent's work never happens.
- Using
super.fieldfor a private field. The compiler rejects it. Use a getter orprotectedaccess if the design allows. - Hiding fields on purpose. It is legal but confusing. Prefer different names.
- Using
superin a static method. There is no object, so there is nosuper.
Quick summary
super.method()runs the superclass version of a method from inside the subclass.super.fieldreaches a superclass field, which matters mainly when a subclass hides it.superfollows normal access rules and goes up only one level.supercannot be used in static code.- Use it to extend parent behavior instead of copying it.
Exercise
In the class below, what does new Cat().describe() print? Then explain what would happen if the line super.describe() were replaced by describe().
class Pet {
String describe() {
return "pet";
}
}
class Cat extends Pet {
@Override
String describe() {
return super.describe() + " cat";
}
}
Show answer
It prints "pet cat" when the result is printed. super.describe() runs Pet's version, which returns "pet", and Cat adds " cat". If super.describe() were replaced by describe(), the method would call itself with no stopping condition. The program would throw a StackOverflowError at runtime.
Exercise
A class Base declares int count = 1; and its subclass Derived declares int count = 2;. Inside a Derived instance method, write the expressions that give 2 and 1. Then say what Base b = new Derived(); b.count gives and why.
Show answer
count (or this.count) gives 2, and super.count gives 1. The expression b.count gives 1. Fields are not overridden, so Java picks the field from the declared type of the variable, which is Base, not from the real object.
Exercise
Why does super.super.speak() not compile, and how can a Puppy class still end up running Animal's speak() method when Puppy extends Dog and Dog extends Animal?
Show answer
Java allows super only for the direct superclass, so there is no way to jump two levels in one expression. A Puppy can still reach Animal's speak() if Puppy calls super.speak() (Dog's version) and Dog's speak() itself calls super.speak(). Each class calls the next one up the chain.