使用场景1
public class person {
private int age;
private String name;
void judge(int a){
if(a>=0&&a<=100){
age=a;
}
else System.out.println("输入的年龄数据有误");
}
void speak(){
System.out.println(name+":"+age+"岁");
}
person(String name){ //这是一个构造函数
this.name=name;
}
person(int age,String name){
this.age=age;
this.name=name;
}
}
public class personDemo {
public static void main(String[] arge){
person a=new person(22,"起个名字好难");
a.speak();
}
}
如程序所示,this.age代表这个对象的age,可以避免因为重名导致两个age都为局部变量的age;
当成员变量和局部变量重名,可以用this来区分。
this:代表对象,当前对象,this就是所在函数中所属对象的引用。
简单说,哪个对象调用了this所在的函数,this就代表哪个对象。如上程序所示,new person(22,“张天麒")调用了this所在的person函数,故this代表person的成员变量,而非构造函数中的局部变量。
使用场景2
person(String name){ //这是一个构造函数
this.name=name;
}
person(String name,int age){
this(name);
this.name=name;
}
如程序所示,当下面那个构造函数调用上面那个构造函数时,可以直接this(name);
需要注意的是,对this的调用必须是构造函数的第一个语句,即对本例来说,不能先this.name=name再this(name);因为初始化的动作要先执行。
this的应用:只要在本类中用到了本类的对象,就要用this,只是在不重名的情况下往往可以省略。