Home >Java >javaTutorial >what does super mean in java

what does super mean in java

下次还敢
下次还敢Original
2024-05-08 08:42:151097browse

The super keyword in Java has three main uses: 1. Calling the parent class constructor; 2. Calling the parent class method; 3. Accessing the parent class fields.

what does super mean in java

Super meaning in Java

Super is a keyword in Java that is used in subclasses Access the methods and fields of the parent class. It has the following main uses:

1. Access the parent class constructor

When a subclass needs to call the parent class's constructor, you can use super() statement. This is usually done in the subclass's constructor. For example:

<code class="java">class Parent {
    int x;
    Parent(int x) {
        this.x = x;
    }
}

class Child extends Parent {
    int y;
    Child(int x, int y) {
        super(x); // 调用父类的构造函数
        this.y = y;
    }
}</code>

2. Calling parent class methods

Subclasses can call parent class methods through the super keyword. This is useful when a subclass needs to reimplement a parent class method. For example:

<code class="java">class Parent {
    void print() {
        System.out.println("父类方法");
    }
}

class Child extends Parent {
    @Override
    void print() {
        super.print(); // 调用父类的方法
        System.out.println("子类方法");
    }
}</code>

3. Accessing parent class fields

Subclasses can also access parent class fields through the super keyword. This is typically used to get the default value of a parent class or to redefine a field of a parent class. For example:

<code class="java">class Parent {
    int x;
}

class Child extends Parent {
    int y;
    Child(int x, int y) {
        super.x = x; // 访问父类的字段
        this.y = y;
    }
}</code>

The above is the detailed content of what does super mean in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn