在说this的用法之前用一句话概括this就是:this代表一个对象,谁调用方法,this就代表谁
this的第一个用法:
在用对象调用方法时,代表调用方法的那个对象,如下示例,对象bei调用shrink方法,所以this在shrink方法中代表的就是对象bei,运行结果如下:
public class Rapper {
private String id;
public void shrink() {
System.out.println(this.id+"正在摇头。。。");
}
public static void main(String[] args) {
Rapper bei=new Rapper();
bei.id="贝贝";
bei.shrink();
}
}
再举一个复杂点的例子:
public class Student {
String name;
void doHomework(){
System.out.println(this.name+"正在做作业.......");
name="刘颖";
}
void speak(){
System.out.println(name+"正在说话......");
}
public static void main(String[] args) {
Student student = new Student();
student.doHomework();
student.speak();
}
}
当对象student调用doHomework方法时,先打印的this.name是声明中默认的null值,而对name赋值的语句,其实前面是省略了this.,所以此时对象student再调用speak方法时,name值已经被赋为“刘颖”,所以运行结果如下:
this的第二个用法:
在构造方法中,用来调用其他构造方法,示例如下:
public class Student {
String name;
public Student(){
System.out.println("无参构造方法");
}
public Student(String name) {
this();
this.name = name;
}
public static void main(String[] args) {
Student student = new Student("法老");
}
}
要注意的是this()只能放在构造方法的第一行,如果this()之前有代码则会报错。
this的第三个用法:
当局部变量的变量名与成员变量的变量名相同,在局部变量作用范围内如果要使用全局变量,则需要用this调用,示例如下:
public class Student {
static String name="贝贝";
public void shrink() {
String name="弹壳";
System.out.println(name);
System.out.println(this.name);
}
public static void main(String[] args) {
new Student().shrink();
}
}
这里有一点要注意就是:This不能用在静态方法中,因为this只能代表对象,但是静态方法的调用可以使用类名,而类名不是对象,也就是说你用this的时候不能保证是对象调用还是类名调用