The super keyword

What is the keyword super and what is it used for?

With the concept of inheritance, in Java not only the constructor of the subclass is called, but also the standard constructor of the superclass. This is because the superclass inherits from the subclass and they are therefore connected. In summary, two constructors are called with one instantiation.

With the help of the super() keyword we can prevent the standard constructor of the superclass from being called. With this you can access the appropriate constructor of the superclass. If you write parameters in the parentheses, the constructor of the superclass that matches the parameters is also searched for and the standard constructor is no longer called. This is similar to overwriting methods . It is important that the constructor of the superclass is processed first, before the subclass is processed further. So if you want to call the superclass, super must be the first statement inside the constructor.

Code Example

This code defines three classes: Book, Dictionary, and Cube.

The Book class has a protected integer field pages, a constructor that sets the pages field, and a print method that prints the number of pages.

The Dictionary class extends the Book class and adds a private integer field words, a constructor that sets both the pages and words fields using the super keyword to call the constructor of the parent Book class, and a message method that calls the print method of the Book class, prints the number of words, and calculates and prints the words per page.

The Cube class has a main method that creates an instance of the Dictionary class with 79 pages and 23,500 words, and then calls the message method on that instance.

class Book {
    protected int pages;

    public Book(int n) {
        pages = n;
    }

    public void print() {
        System.out.println("Number of pages: " + pages);
    }
};

class Dictionary extends Book {
    private int words;

    public Dictionary(int pages, int w) {
        super(pages);
        words = w;
    }

    public void message() {
        super.print();
        System.out.println("Number of words: " + words);
        System.out.println("Words per page: " + words / pages);
    }
};

class Cube {
    public static void main(String[] args) {
        Dictionary obj = new Dictionary(79, 23500);
        obj.message();
    }
}
Output
Number of pages: 79
Number of words: 23500
Words per page: 297