this代表对当前对象的一个引用,用于调用属性,方法,及本类中构造方法。具体如下
1.在方法中用this调用成员变量,解决与局部变量的重名问题
this在实例方法中通常被省略,除非实例方法中包含与成员变量同名的局部变量时,访问成员变量需要使用this。
public class Student{
String name="Tom" ;
public Student(String name ) {
System.out.println(name+"在说话");
System.out.println(this.name+"在学习");
}
public static void main(String[] args) {
Student stu = new Student("Jim");
}
}
运行结果
Jim在说话
Tom在学习(可见this可用来代表成员变量)
2.用this调用成员方法
public class Student {
private String name;
public void doHomework(){
System.out.println(this);//谁调用此方法,this代表谁
System.out.println(this.name+"正在做作业......");
}
public static void main(String[] args) {
Student stu = new Student();//将地址赋值给stu
System.out.println(stu);
stu.name = "Tom";//通过student变量的地址找到相应的对象
stu.doHomework();
}
}
3.用this调用构造方法
public class Student {
int age;
String name;
public Student(int age) {
this.age = age;
}
public Student(String name) {
this.name = name;
}
public Student(int age, String name) {
this(age);
// Student stu = new Student(name);
// System.err.println(stu.age);
this.name = name;
}
public static void main(String[] args) {
Student student = new Student(12, "王五");
System.out.println(student.age);
System.out.println(student.name);
}
}
注:用this调用构造方法时,this只能放在构造方法第一行,只能出现一次,不能在两个构造方法中互相调用
运行结果:
注释掉两行后结果:12,王五
未注释两行,删去this.name = name后,结果:12,null,0
注意:关键字this不能在被static修改的方法中使用,因为static修饰的方法可以用类名调用,调用时不能确定是对象调用还是类调用,不能保正调用方法的一定是对象,而this只能表示对象