this 关键字
this.类变量
将方法的参数值赋予类中的成员变量。
Public void setName(String name)
{
this.name= name;
}
在上述的代码中,成员变量与setName()方法中的形式参数的名称相同,都为name,那么该如何在类中区分使用的是哪个变量呢?
在java语言中规定使用this关键字来代表本类对象的引用(this是属于一个具体的对象,不是类的),关键字被隐式地用于引用对象成员和方法。如在上述代码中,this.name指的就是类中的name变量,而this.name = name 语句中的第二个name则指的是形参name。
事实上,this引用的就是本类的一个对象,在局部变量或方法参数覆盖成员变量时,如上述代码的情况,就要添加this关键字明确引用的是类成员还是局部变量或是方法参数。
public classDemo9_15 {
public static void main(String[] args) {
Dogdog1= newDog(1,"大黄");
Person p1 = new Person(dog1,23,"小明");
Person p2 = new Person(dog1,22,"大明");
p1.showInfo();
}
}
class Person
{
intage;
String name;
Dog dog;
publicPerson(Dog dog,intage,Stringname)
{
this.age = age;
this.name = name;
this.dog = dog;
}
publicvoidshowInfo()
{
System.out.println("名字:" + this.name);
System.out.println("年龄:" + this.age);
}
}
class Dog
{
intage;
String name;
publicDog(intage,String name)
{
this.name = name;
this.age = age;
}
}
结果截图