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).
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:
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.
If the parent class does not have a parameterless constructor, the subclass must explicitly call the parent class's parameterized 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!