Home > Java > javaTutorial > body text

Usage of super keyword in java

下次还敢
Release: 2024-05-01 17:15:31
Original
645 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template