Java this 与 super 关键字
this 和 super 是 Java 中两个重要的关键字,用于引用当前对象和父类对象。理解它们的使用是掌握面向对象编程的关键。本章将详细介绍 this 和 super 的用法。
this 关键字
this 的作用
this 表示当前对象的引用,用于:
- 区分参数和成员变量
- 调用其他构造方法
- 返回当前对象
- 传递当前对象
区分参数和成员变量
最常见用法:当参数名和成员变量名相同时,使用 this 区分。
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name; // this.name 是成员变量,name 是参数
this.age = age; // this.age 是成员变量,age 是参数
}
public void setName(String name) {
this.name = name; // 区分参数和成员变量
}
}
不使用 this 的情况:
public class Student {
private String name;
public void setName(String studentName) {
name = studentName; // 参数名不同,不需要 this
}
}
调用其他构造方法
使用 this() 调用同一类的其他构造方法:
public class Student {
private String name;
private int age;
private String studentId;
// 无参构造
public Student() {
this("