本我过去在哪里,自我即应在哪里。---弗洛伊德
总要有个事物来代表类的当前对象,就像C++中的this指针一样,Java中的this关键字就是代表当前对象的引用。
它有三个主要的作用:
1、在构造方法中调用其他构造方法。
比如有一个Student类,有三个构造函数,某一个构造函数中调用另外构造函数,就要用到this(),而直接使用Student()是不可以的。
2、返回当前对象的引用。
3、区分成员变量名和参数名。
看下面的例子:
public class Student
{
private String name;
private int age;
private String college;
public Student()
{
age = 20;
}
public Student(String name)
{
this();//can not be call Student,only use this() method.
this.name = name;
System.out.println("this student name is "+name);
}
public Student(String name,String college)
{
this(name);//C++中可以直接用Student(name)调用其他构造函数
this.college = college;
System.out.println("this student name is "+name+" college is "+college);
}
public Student upgrade()
{
age++;
return this;
}
public void print()
{
System.out.println("name is: "+name
+" age is: "+age
+" college is: "+college);
}
public static void main(String[] args)
{
Student student1 = new Student("linc");
Student student2 = new Student("linc","shenyang college");
student2.upgrade().print();
}
}
迷失在茫茫的对象海洋时,不要忘了用this来找到自我。
本文深入解析Java中的this关键字,阐述其在构造方法、返回当前对象引用及区分成员变量名与参数名方面的重要作用,并通过实例代码进行详细演示。

被折叠的 条评论
为什么被折叠?



