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

What does super() mean in java

下次还敢
下次还敢Original
2024-04-27 00:15:251117browse

The super() keyword is used to call the constructor of the parent class in the Java subclass constructor to ensure that the parent class instance variables are correctly initialized. The syntax is super() (no parameters) or super (parameters).

What does super() mean in java

super(): The parent class constructor call in Java

In Java, super The () keyword is used to call the constructor of the parent class. It is the first statement in the subclass constructor and is responsible for initializing the instance variables of the parent class.

Why do we need to call the parent class constructor?

When a subclass is instantiated, Java first calls the constructor of the parent class. This ensures that the parent class's instance variables are initialized correctly. If the child class does not explicitly call the parent class constructor, Java will automatically call the no-argument constructor. But it is recommended to call the parent class constructor explicitly as it clearly specifies the constructor to be called and avoids unexpected behavior.

Syntax:

super() Keyword can be taken with or without parameters:

  • No parameters: Call the parameterless constructor of the parent class.
  • With parameters: Call the parameterized constructor of the parent class, where the parameters correspond to the parameters in the parent class constructor.

Example:

<code class="java">// 父类 Animal
class Animal {
    private String name;

    public Animal(String name) {
        this.name = name;
    }
}

// 子类 Dog
class Dog extends Animal {
    private int age;

    public Dog(String name, int age) {
        // 调用父类的带参构造函数
        super(name);
        this.age = age;
    }
}</code>

In the above example, super(name ), which passes the name parameter to the parameterized constructor of the parent class Animal. This ensures that the name instance variable of the Animal class is initialized correctly.

Note:

    super()
  • must be the first statement in the subclass constructor. If the parent class does not have a parameterless constructor, the subclass must explicitly call the parent class's parameterized constructor.
  • If the subclass constructor does not call the parent class constructor, Java will automatically call the parent class's no-argument constructor.

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