Home  >  Article  >  Java  >  The role of this and super in java

The role of this and super in java

下次还敢
下次还敢Original
2024-05-01 18:48:15883browse

this refers to the current object, and super refers to the parent class. This is used to access members of the current class, while super is used to access members of the parent class and is used in class constructors and methods. Understanding them is crucial and helps write clear Java code.

The role of this and super in java

The role of this and super in Java

In Java, this and super are two key keywords used to access objects in the class and members of the parent class.

this keyword

  • Purpose: Reference the current object.
  • Usage: Used in methods and constructors of a class to access instance variables and methods of the current class.
  • Example:
<code class="java">class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }
}</code>

super keyword

  • Purpose: Reference to the parent class.
  • Usage: Use in methods and constructors of subclasses to access members of the parent class.
  • Example:
<code class="java">class Employee extends Person {
    private double salary;

    public Employee(String name, double salary) {
        super(name);  // 调用父类的构造函数
        this.salary = salary;
    }

    public double getSalary() {
        return this.salary;
    }
}</code>

Difference between this and super

  • this refers to the current object, while super refers to the parent class.
  • this is used to access members of the current class, while super is used to access members of the parent class.
  • this is usually used in constructors and methods, while super is mainly used in subclasses.

Understanding the role of this and super is critical to writing clear, maintainable Java code. It helps in accessing and manipulating members of classes and parent classes, thereby enabling object-oriented programming.

The above is the detailed content of The role of 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