Home > Java > javaTutorial > The functions and methods of super in java

The functions and methods of super in java

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

super is used in Java to access parent class members, including constructors, methods and variables, and can also override parent class methods. 1. Call the parent class constructor: use super() in the subclass to call the parent class's constructor; 2. Access the parent class method: use super.method() to call the parent class method; 3. Access the parent class variable: use super.variable accesses the variables of the parent class; 4. Override the parent class method: by defining an override method in the subclass with the same signature as the parent class.

The functions and methods of super in java

The functions and methods of super in Java

super is a key in Java Words, mainly used for the following functions:

1. Access parent class members

  • Call parent class constructor
  • Access parent class methods
  • Access parent class variables

2. Override parent class methods

By defining a variable in the subclass with the same signature as the parent class Methods can override parent class methods. At this time, the super keyword is used to call the method of the parent class.

Usage method

1. Call the parent class constructor

<code class="java">public class Child extends Parent {
    public Child() {
        super(); // 调用父类无参构造函数
    }
}</code>
Copy after login

2. Access the parent class method

<code class="java">public class Child extends Parent {
    public void printMessage() {
        super.printMessage(); // 调用父类 printMessage() 方法
    }
}</code>
Copy after login

3. Access parent class variables

<code class="java">public class Child extends Parent {
    public void printName() {
        System.out.println("父类变量:" + super.name);
    }
}</code>
Copy after login

4. Override parent class methods

<code class="java">public class Child extends Parent {
    @Override
    public void printMessage() {
        super.printMessage(); // 调用父类方法
        System.out.println("子类覆盖后的消息!");
    }
}</code>
Copy after login

The above is the detailed content of The functions and methods of super in java. For more information, please follow other related articles on the PHP Chinese website!

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