Java 学习32:this 关键字
一、什么是 this
在 Java 中,this 是一个关键字,它代表当前对象的引用。也就是说,this 指向调用当前方法或构造方法的那个对象。
this 关键字可以在类的成员方法和构造方法中使用,主要有三种用法:
- 区分成员变量和局部变量
- 调用本类的其他构造方法
调用本类的其他方法(通常可省略)
二、this 的主要用法
1. 区分成员变量与局部变量
当方法的参数名称和类的成员变量名称相同时,用 this.变量名 可以明确指代类的成员变量。
public class Person {private String name;public void setName(String name) {this.name = name; // this.name表示成员变量,name表示参数}
}2. 调用本类的其他构造方法
public class Person {private String name;private int age;// 无参构造public Person() {this("未知", 0); // 调用带两个参数的构造方法}// 带参构造public Person(String name, int age) {this.name = name;this.age = age;}
}3. 调用本类的其他方法(通常可省略)
public class Example {public void methodOne() {//}public void methodTwo() {this.methodOne(); // 用this调用methodOne(),可以省略this,直接写作methodOne()}
}三、this 使用注意事项
- 在构造方法中调用 this(...) 时,this(...) 必须是第一条语句。
- this 关键字不能在静态方法中使用,因为静态方法不依赖于对象。
- 在构造方法中,this(...) 和 super(...) 不能同时使用,因为它们都必须是第一条语句。
