Home  >  Article  >  Java  >  What does super mean in java

What does super mean in java

下次还敢
下次还敢Original
2024-05-01 18:51:34949browse

The super keyword in Java is used to access the constructor, methods and fields of the parent class: Member access: super() calls the parent class constructor. Method access: super.method() calls the parent class method. Field access: super.field accesses parent class fields.

What does super mean in java

super in Java

super is a keyword in Java that is used to access members of the parent class . In a subclass, use the super keyword to access the constructor, methods, and fields of the parent class.

Member access

  • Constructor: Use super() to call the parent class constructor in the subclass constructor. This is typically used to initialize parent class members and implement polymorphism.
  • Method: Use super.method() to call the method of the parent class. This is mainly used to override parent class methods or call parent class implementations.
  • Field: Use super.field to access the fields of the parent class. It should be noted that if a subclass also has a field with the same name, the subclass field will be accessed first.

Usage

The super keyword is usually used in the following situations:

  • Calling the parent class constructor to initialize the parent class members .
  • Override parent class methods to achieve polymorphism.
  • Access fields in the parent class that cannot be overridden or hidden in the subclass.

Example

<code class="java">class Parent {
    private int age;

    public Parent(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }
}

class Child extends Parent {
    public Child(int age) {
        super(age); // 调用父类构造函数
    }

    @Override
    public int getAge() {
        return super.getAge() + 1; // 覆盖父类方法并调用父类实现
    }
}</code>

In this example, the subclass Child initializes the age field of the parent class by calling the constructor of the parent class Parent through super(age) . It also achieves polymorphism by calling the getAge() method of the parent class through super.getAge().

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!

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