this
this关键字
this代表当前对象的一个引用
所谓当前对象,指的是调用类中方法或属性的那个对象
this只能在方法内部使用,表示对“调用方法的那个对象” 的引用
this关键字调用本类属性变量
this.属性名:表示本对象自己的属性
当参数列表中的变量名与对象的成员变量名一致时,对象的属性会被方法或构造器的参数屏蔽。这个时候,我们就可以使用 this.属性名 来代替成员变量。
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
}
this关键字调用本类方法
方法调用本类方法
this.方法名: 表示当前对象自己的方法
public class Student {
public void eat() {
System.out.println("同学们吃点食物");
}
public void talk() {
this.eat();
System.out.println("同学们吃完再说");
}
}
构造方法调用本类方法
public class Student {
private String name;
private String sex;
private int age;
public Student() {
this.init();
}
public void init() {
System.out.println("对象初始化!");
this.sex = "男";
}
}
构造方法调用本类的构造方法
this关键字必须位于构造函数的第一行。
public class Student {
private String name;
private String sex;
private int age;
public Student() {
this.init();
}
public Student(String name, int age) {
this();
this.name = name;
this.age = age;
}
public void init() {
System.out.println("对象初始化!");
this.sex = "男";
}
}
调用有参构造函数是这样的:
public Student() {
this("小明", 20);
this.init();
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
this关键字使用注意
this关键字不能用于静态方法和静态块
main方法也是静态的,所以this也不能用于main方法