1. Introduction

In this quick tutorial, we’ll take a look at the super Java keyword.

Simply put, we can use the super keyword to access the parent class. 

Let’s explore the applications of the core keyword in the language.

2. The super Keyword With Constructors

We can use super() to call the parent default constructor. It should be the first statement in a constructor.

In our example, we use super(message) with the String argument:

public class SuperSub extends SuperBase {

    public SuperSub(String message) {
        super(message);
    }
}

Let’s create a child class instance and see what’s happening behind:

SuperSub child = new SuperSub("message from the child class");

The new keyword invokes the constructor of the SuperSub, which itself calls the parent constructor first and passes the String argument to it.

3. Accessing Parent Class Variables

Let’s create a parent class with the message instance variable:

public class SuperBase {
    String message = "super class";

    // default constructor

    public SuperBase(String message) {
        this.message = message;
    }
}

Now, we create a child class with the variable of the same name:

public class SuperSub extends SuperBase {

    String message = "child class";

    public void getParentMessage() {
        System.out.println(super.message);
    }
}

We can access the parent variable from the child class by using the super keyword.

4. The super Keyword With Method Overriding

Before going further, we advise reviewing our method overriding guide.

Let’s add an instance method to our parent class:

public class SuperBase {

    String message = "super class";

    public void printMessage() {
        System.out.println(message);
    }
}

And override the printMessage() method in our child class:

public class SuperSub extends SuperBase {

    String message = "child class";

    public SuperSub() {
        super.printMessage();
        printMessage();
    }

    public void printMessage() {
        System.out.println(message);
    }
}

We can use the super to access the overridden method from the child class. The super.printMessage() in constructor calls the parent method from SuperBase.

5. Conclusion

In this article, we explored the super keyword.

As usual, the complete code is available over on Github.


« 上一篇: Java关键字"this"指南