Java 关键字 This的使用
this表示当前对象,可以调用类的属性、方法和构造器
1.this 是什么
- 在方法内部使用,即这个方法所属对象的引用
- 在构造方法内部使用,表示该构造方法正在初始化的对象
2.什么时候使用this 关键字
- 当在方法内需要用到调用该方法的对象时,就用this
- 具体的我们可以用this来区分局部变量和属性
3.code举例
class Person {
private String name;
private int age;
//空参构造方法
public Person() {
System.out.println("状态初始化...");
}
public Person(String name, int age) {
// 调用无参的构造方法 初始化对象,也可以传参表示调用有参的构造方法
this();
// this 表示当前正在创建的对象
this.name = name;
this.age = age;
this.eat();
}
public String getName() {
return name;
}
public void setName(String name) {
// this 表示当前对象
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
// this 表示当前对象
this.age = age;
}
public void eat() {
System.out.println(name + " 会吃饭");
// 表示当前对象
this.study();
}
public void study() {
System.out.println(age + " 岁年龄的人爱睡觉");
}
}