Home >Java >javaTutorial >What is the use of super in java

What is the use of super in java

下次还敢
下次还敢Original
2024-05-09 05:57:15505browse

There are two ways to use super in Java: 1. Access member variables of the parent class; 2. Call methods of the parent class.

What is the use of super in java

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:

  • super can only be used in instance methods of subclasses, not static methods.
  • The super call must be in the first line of the constructor or instance method of the subclass.
  • The super keyword can help achieve polymorphism and code reuse.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn