The super keyword is used in subclasses to access member variables, methods or constructors of the parent class. Its main uses include: 1. Access parent class member variables 2. Call parent class methods 3. Call parent class constructor. The super keyword can only be used in subclasses, and must be used in the context of an instance of the subclass.
Usage of super keyword in Java
What is super keyword?
The super keyword is used in Java to refer to member variables, methods or constructors of the parent class.
Uses of super keyword
The super keyword has the following main uses:
1. Access parent class member variables
To access the member variables of the parent class, you can use the super.member_variable syntax. For example:
<code class="java">class Child extends Parent { int childVariable; void accessParentVariable() { System.out.println("Parent variable: " + super.parentVariable); } }</code>
2. Call the parent class method
To call the parent class method, you can use the super.method_name() syntax. For example:
<code class="java">class Child extends Parent { void childMethod() { super.parentMethod(); } }</code>
3. Call the parent class constructor
To call the parent class constructor, you can use the super() syntax, which must be in the subclass constructor The first line of the call. For example:
<code class="java">class Child extends Parent { public Child() { super(); // 调用父类的无参构造函数 } public Child(int value) { super(value); // 调用父类的带参构造函数 } }</code>
Use of super keyword Note
The above is the detailed content of Usage of super keyword in java. For more information, please follow other related articles on the PHP Chinese website!