Home  >  Article  >  Java  >  The difference between this and super in java

The difference between this and super in java

下次还敢
下次还敢Original
2024-05-01 18:46:02970browse

This points to the current object, used to access its methods and properties, and is often used in constructors; super points to the parent class, used to call parent class methods or access its properties, and is often used to override parent class methods or access Properties that are not overridden.

The difference between this and super in java

The difference between this and super in Java

This and super are both keywords in Java , which are used to access methods and properties of a class.

this

  • this keyword is used to refer to the current object.
  • It allows you to access the methods and properties of the current object without explicitly specifying the object name.
  • is often used in constructors to initialize object state.

super

  • super keyword is used to refer to the parent class.
  • It allows you to call the parent class's methods and access the parent class's properties.
  • is often used to override parent class methods or access properties of the parent class that are not overridden by the subclass.

Main differences

Features this super
Purpose Reference the current object Reference the parent class
Scope Current class Parent class
Syntax this.propertyName/methodName super.propertyName/methodName
Initialization Initialize the object state in the constructor Access the constructor of the parent class
Override Method cannot be used to override parent class methods can be used to override parent class methods

Example

<code class="java">class Parent {
    public void printName() {
        System.out.println("Parent");
    }
}

class Child extends Parent {
    @Override
    public void printName() {
        System.out.println("Child");
    }

    public void callSuper() {
        super.printName(); // 调用父类的方法
    }
}</code>

Output:

<code>Child
Parent</code>

The above is the detailed content of The difference between this and 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