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
In Java, this and super are two key keywords used to access objects in the class and members of the parent class.
this keyword
<code class="java">class Person { private String name; public Person(String name) { this.name = name; } public String getName() { return this.name; } }</code>
super keyword
<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
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!