Home  >  Article  >  Java  >  Usage of super keyword in java

Usage of super keyword in java

下次还敢
下次还敢Original
2024-05-01 17:15:31602browse

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

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 super keyword can only be used in subclasses.
  • The super keyword must be used in the context of an instance of a subclass.
  • The super keyword can only call member variables, methods or constructors of the parent class, but cannot be used to access or call members of the ancestor class.

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!

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