在类中,可以使用this关键字表示一些特殊的作用。
1)区别成员变量和局部变量
public class Student{
private String name;
public void setName(String name){
//this.name表示类中的属性name
this.name = name;
}
}
2)调用类中的其他方法
public class Student{
private String name;
public void setName(String name){
this.name = name;
}
public void print(){
//表示调用当前类中的setName方法
this.setName("tom");
}
}
注:默认情况下,setName("tom")和this.setName("tom")的效果是一样的.
3)调用类中的其他构造器
public class Student{
private String name;
public Student(){
//调用一个参数的构造器,并且参数的类型是String
this("tom");
}
public Student(String name){
this.name = name;
}
}
注:this的这种用法,只能在构造器中使用.普通的方法种是不能只有用的.并且这局调用的代码只能出现在构造器中的第一句.
例如:
public class Student{
private String name;
//编译报错,因为this("tom")不是构造器中的第一句代码.
public Student(){
System.out.println("hello");
this("tom");
}
public Student(String name){
this.name = name;
}
}
4)this关键字在类中的意义
this在类中表示当前类将来创建出的对象.
例如:
public class Student{
private String name;
public Student(){
System.out.println("this = "+this);
}
public static void main(String[] args){
Student s = new Student();
System.out.println("s = "+s);
}
}
运行后看结果可知,this和s打印的结果是一样的,那么其实也就是变量s是从对象的外部执行对象,而this是在对象的内部执行对象本身.
这样也就能理解为什么this.name代表的是成员变量,this.setName("tom")代表的是调用成员方法,因为这俩句代码从本质上讲,和在对象外部使用变量s来调用是一样的,s.name和s.setName("tom")。
this和s打印出来的内存地址是一样的,使用==比较的结果为true。
例如:
public class Student{
public Student getStudent(){
return this;
}
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = s1.getStudent();
System.out.println(s1 == s2);//true
}
}
例如: 类中的this是和s1相等还是和s2相等呢?
public class Student{
private String name;
public void test(){
System.out.println(this);
}
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
s1.test();
s2.test();
}
}
注:这句话是要这么来描述的,s1对象中的this和s1相等,s2对象中的this和s2相等,因为类是模板,模板中写的this并不是只有一个,每个对象中都有一个属于自己的this,就是每个对象中都一个属于自己的name属性一样.