AI Hints
Home›Java Tutorial›Encapsulation, Inheritance and super
Java · Lesson 75 of 120

super

Talk to the parent.

⏱ 2 min read▶ Video at 1:34:27🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Inside a child class, the word super means the parent part of this object. You use it to call the parent's constructor, or its methods.

  • super
  • The parent part
  • Constructor or methods

Cat.java

Cat adds a field, lives. Its constructor first calls super, with the name, so Animal can set it up. That must be the first line. Then it sets its own field. In describe, super dot eat calls the parent's eat method.

Main.javajava
public class Cat extends Animal {
    private int lives;

    public Cat(String name, int lives) {
        super(name);
        this.lives = lives;
    }

    public void describe() {
        super.eat();
        System.out.println(name + " has " + lives + " lives.");
    }
}

Using Cat

We create a cat, with nine lives. Run it. Tom eats, using Animal's method, and then reports his lives.

Main.javajava
public class Main {
    public static void main(String[] args) {
        Cat tom = new Cat("Tom", 9);
        tom.describe();
    }
}
Output
Tom is eating.
Tom has 9 lives.
Also uses Animal.java
public class Animal {
    protected String name;

    public Animal(String name) { this.name = name; }

    public void eat() {
        System.out.println(name + " is eating.");
    }
}
Also uses Cat.java
public class Cat extends Animal {
    private int lives;

    public Cat(String name, int lives) {
        super(name);
        this.lives = lives;
    }

    public void describe() {
        super.eat();
        System.out.println(name + " has " + lives + " lives.");
    }
}

super rules

Super with brackets calls the parent's constructor. It must be the very first line of the child's constructor. If you don't write it, Java calls the empty parent constructor for you. And super dot method calls the parent's version of a method.

keyvalue
super(...)parent constructor
Wherefirst line
Left outsuper() added for you
super.m()parent's method

Summary

Super calls the parent's constructor, on the first line, and super dot method calls the parent's methods. Next, replacing a parent's method, with overriding.

Key takeaways
  • super(name)
  • First line
  • super.eat()
Next up: Overriding — replace a parent method