this关键字
this调用属性、方法
一、背景:
* 当属性和局部变量名字相同时,如何在方法内或构造器内区分属性和局部变量呢?
*
* 二、this:理解为当前对象或当前正在创建的对象
*
* 三、使用this可以在方法内、构造器内修饰、调用:属性、方法:
*
* 1. 在方法内部,为了区分属性和局部变量,我们使用this来修饰此同名的变量,表示此变量是属性,而非局部变量。
* this,表示的就是调用当前方法的对象。
* 比如:p1.setName("Tom"),此时setName()中的this就表示p1.
*
* 2. 在构造器内部,为了区分属性和局部变量,我们使用this来修饰此同名的变量,表示此变量是属性,而非局部变量。
* this,表示的就是调用当前方法的正在创建的对象。
this调用构造器
四、使用this修饰: 构造器
* 1. 在类的构造器中,可以使用"this(形参列表)"的方式,调用本类中重载的其它构造器
* 2. 如果一个类中有n个构造器,则最多有 n - 1个构造器中使用了"this(形参列表)"
* 3. 要求:"this(形参列表)"的声明必须写在构造器的首行。
* 4. 一个构造器中,最多只能声明一个"this(形参列表)"
代码演示:
public class PersonTest {
public static void main(String[] args) {
Person p1 = new Person("Tom",12);
p1.setName("Jerry");
p1.setAge(32);
p1.show();
Person p2 = new Person();
p2.setAge(12);
p2.eat();
}
}
class Person{
private String name;
private int age;
public Person(){
System.out.println("========Person()=========");
}
public Person(String n){
this();
name = n;
}
public Person(String name,int age){
this();
this.name = name;
this.age = age;
}
public void show(){
System.out.println("name :" + name + ", age :" + age);
}
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age = age;
}
public void eat(){
System.out.println("吃饭");
this.sleep();
}
public void sleep(){
System.out.println("睡觉");
}
}