Home >Java >javaTutorial >The functions and methods of super in java
super is used in Java to access parent class members, including constructors, methods and variables, and can also override parent class methods. 1. Call the parent class constructor: use super() in the subclass to call the parent class's constructor; 2. Access the parent class method: use super.method() to call the parent class method; 3. Access the parent class variable: use super.variable accesses the variables of the parent class; 4. Override the parent class method: by defining an override method in the subclass with the same signature as the parent class.
The functions and methods of super in Java
super is a key in Java Words, mainly used for the following functions:
1. Access parent class members
2. Override parent class methods
By defining a variable in the subclass with the same signature as the parent class Methods can override parent class methods. At this time, the super keyword is used to call the method of the parent class.
Usage method
1. Call the parent class constructor
<code class="java">public class Child extends Parent { public Child() { super(); // 调用父类无参构造函数 } }</code>
2. Access the parent class method
<code class="java">public class Child extends Parent { public void printMessage() { super.printMessage(); // 调用父类 printMessage() 方法 } }</code>
3. Access parent class variables
<code class="java">public class Child extends Parent { public void printName() { System.out.println("父类变量:" + super.name); } }</code>
4. Override parent class methods
<code class="java">public class Child extends Parent { @Override public void printMessage() { super.printMessage(); // 调用父类方法 System.out.println("子类覆盖后的消息!"); } }</code>
The above is the detailed content of The functions and methods of super in java. For more information, please follow other related articles on the PHP Chinese website!