Home  >  Article  >  Java  >  What does super() mean in java

What does super() mean in java

下次还敢
下次还敢Original
2024-05-08 08:03:19328browse

super() allows subclasses to call parent class constructors or methods to reuse parent class functions, ensure that the subclass state is correctly initialized, and achieve polymorphism.

What does super() mean in java

super() in Java

super() is a special function in Java Method, used to call the constructor or method of the parent class.

Usage

Call super() in the constructor

super() must be used in the constructor of the subclass as The first statement calls to call the constructor of the parent class. This ensures that the parent class's constructor is executed before the child class's constructor, thus properly initializing the parent class state.

Example:

<code class="java">class Parent {
    int num;

    Parent(int num) {
        this.num = num;
    }
}

class Child extends Parent {
    int score;

    Child(int num, int score) {
        super(num);  // 调用父类的构造函数
        this.score = score;
    }
}</code>

Calling super() in a method

super() can also be used in a method to call Methods of the parent class. This allows subclasses to override parent class methods while still having access to the parent class implementation.

Example:

<code class="java">class Parent {
    void sayHello() {
        System.out.println("Hello from Parent");
    }
}

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

Advantages

  • Scalability: super() Allows reuse of parent class functionality without duplicating code.
  • Robustness: By calling the constructor of the parent class, super() ensures that the child class state is correctly initialized.
  • Polymorphism: super() allows subclasses to override parent class methods, thereby achieving polymorphism.

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