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.
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
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!