Guide to the super Java Keyword – Super Java关键词指南

最后修改: 2018年 6月 2日

中文/混合/英文(键盘快捷键:t)

 

1. Introduction

1.介绍

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

在这个快速教程中,我们将看一下superJava关键字。

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

简单地说,我们可以使用super关键字来访问父类。

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

让我们来探讨语言中核心关键词的应用。

2. The super Keyword With Constructors

2.使用构造器的super关键字

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

我们可以使用 super()来调用父级默认构造函数。它应该是构造函数中的第一个语句。

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

在我们的例子中,我们使用super(message) String参数。

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.

new关键字调用SuperSub的构造函数,它本身首先调用父级构造函数并将String参数传递给它。

3. Accessing Parent Class Variables

3.访问父类变量

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

让我们创建一个带有message实例变量的父类。

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.

我们可以通过使用super关键字从子类访问父类变量。

4. The super Keyword With Method Overriding

4.使用方法重写的super关键字

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:

并在我们的子类中覆盖printMessage()方法。

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.

我们可以使用super来访问来自子类的重写方法。构造函数中的super.printMessage()调用SuperBase的父方法。

5. Conclusion

5.结论

In this article, we explored the super keyword.

在这篇文章中,我们探讨了super关键词。

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

像往常一样,完整的代码可以在Github上找到