CodeBlanks Logo Icon CodeBlanks

super

Learn to call the parent with super.

The super keyword

To call the superclass constructor from a subclass constructor, use super(...). The super() call must be the first statement in the subclass constructor. This is how you initialize the superclass's fields.

Example: class Cat extends Animal { Cat(String n) { super(n); } }. Here the Cat constructor calls the Animal constructor with super(n) and initializes name in the superclass. super also accesses superclass methods: super.eat(). This lets you call an overridden method's superclass version.

The position of super()

The super() call must always be the first statement in a subclass constructor. This is mandatory; otherwise you get a compile error. The superclass's fields must be initialized before the subclass's own fields.

Example: Cat(String n) { super(n); int age = 0; }. Here super(n) comes first, then age assignment. If you write super(n) after the age assignment, a compile error occurs. This order ensures the superclass is ready first; the subclass body knows the superclass is prepared.

Practice Add super to the Cat class

Define a class Animal with a String name field and an Animal(String n) constructor that assigns name = n;. Define Cat extends Animal whose Cat(String n) constructor starts with super(n). Put main inside Cat; create a Cat instance and print its name field.

Starter code

Main.java
// Define the Animal class
// Define Cat extends Animal with the superclass call
// Instantiate and print in main

Sample solution

Main.java
class Animal {
    String name;
    Animal(String n) {
        name = n;
    }
}
class Cat extends Animal {
    Cat(String n) {
        super(n);
    }
    public static void main(String[] args) {
        Cat c = new Cat("Whiskers");
        System.out.println(c.name);
    }
}

Expected output

Whiskers

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the super uses

Term Meaning
super(n) Superclass constructor
super.eat() Superclass method
first line Position principle
Animal Superclass

2 Where must the super() call be?

  • Inside a method body
  • At the first line of the constructor Correct answer
  • At the last line of the constructor
  • Outside the class

Explanation: At the first line of the constructor — super() must be first.

3 Complete the super() call

Question
class Cat extends Animal {
    Cat(String n) {
        ____(n);
    }
}
Answer
class Cat extends Animal {
    Cat(String n) {
        super(n);
    }
}

Explanation: super(n) calls the superclass constructor.

All lessons in Intermediate