Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

the super keyword is used in subclasses to

  • call the superclass constructors
  • access superclass members
class Animal {
    String name = "Animal";
    void eat() {
        System.out.println("Animal eats.");
    }
}

class Dog extends Animal {
    String name = "Dog";
    void eat() {
        super.eat(); // Call superclass method
        System.out.println("Dog eats bones.");
    }
    void display() {
        System.out.println("Superclass name: " + super.name); // Access superclass field
    }
}

class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();    // Output: Animal eats. Dog eats bones.
        dog.display(); // Output: Superclass name: Animal
    }
}