Home >Java >javaTutorial >What is the use of super in java
There are two ways to use super in Java: 1. Access member variables of the parent class; 2. Call methods of the parent class.
Usage of super in Java
super is a keyword in Java. Used to access member variables and methods of the parent class. It has two main uses:
1. Access the member variables of the parent class
super can be used to access the member variables of the parent class, even if these variables are in the subclass is covered. For example:
<code class="java">class Parent { protected int age; } class Child extends Parent { @Override protected int age; public void printAge() { System.out.println(super.age); // 访问父类的 age 变量 } }</code>
2. Calling methods of the parent class
super can also be used to call methods of the parent class, even if these methods are overridden in the subclass. For example:
<code class="java">class Parent { public void speak() { System.out.println("Hello!"); } } class Child extends Parent { @Override public void speak() { super.speak(); // 调用父类的 speak() 方法 System.out.println("My name is..."); } }</code>
Note:
The above is the detailed content of What is the use of super in java. For more information, please follow other related articles on the PHP Chinese website!