this关键字的用法类似于python中的self,它可以替代引用名,指向对象本身。
举个例子:
public class Scores
{
int maths;
int English;
int Chinese;
public Scores(){}//记得补上一个无参的构造方法
public Scores(int maths, int English, int Chinese)
{
maths = maths;
English = English;
Chinese = Chinese;
}
public void Scores_print()
{
System.out.println(maths);
System.out.println(English);
System.out.println(Chinese);
}
}
然后在test中调用这个类:
public class test
{
public static void main(String[] args)
{
Scores score = new Scores(120,130,140);
score.Scores_print();
}
}
结果如下:
可以看到结果为3个0,但是我们明明给了120/130/140三个数字进去,为什么结果会是3个0呢?
还记不记得前面说的,Java中遵循就近原则。
所以在语句:
maths = maths;
English = English;
Chinese = Chinese;
执行的时候,是将构造方法的形参的值付给了形参自己,所以这三句语句等于什么都没有执行,而maths等成员变量的值没有被修改,为默认值0;
但是如果我们这么写test中的代码:
public class test
{
public static void main(String[] args)
{
Scores score = new Scores();//使用无参的构造方法
score.maths = 120;
score.Chinese = 130;
score.English = 140;
score.Scores_print();
}
}
结果如下:
可以看到成功将值付给了对象中的3个变量。
但是如果我们想用构造方法直接传入数值,应该怎么做呢?
我们可以这么改Scores中的代码:
public class Scores
{
int maths;
int English;
int Chinese;
public Scores(){}//记得补上一个无参的构造方法
public Scores(int maths, int English, int Chinese)
{
//在每个变量前加上this关键字
this. maths = maths;
this. English = English;
this. Chinese = Chinese;
}
public void Scores_print()
{
System.out.println(maths);
System.out.println(English);
System.out.println(Chinese);
}
}
然后将test中的代码改回原本的代码,结果如下
可以看到成功得到了结果
所以,this.其实替代了score.,也就是说,this和score这个引用名指向同一个地址,如果引用名改成别的什么比如说score2,那么this就和score2相同。
换句话说,this就相当于对象的引用名,只是在我们编写类的时候,并不知道用户会用取什么样的引用名。所以我们使用this来指代引用名。



