先看下面一段代码:
// lesson8
//necessary of 'this'
class Person
{
int age;
String name;
//constructor
public Person(int age, String name)
{
this.age=age;
this.name= name;
}
//show name
public void showInfo()
{
System.out.println("name is:"+name); //如果构造方法里不用this,这里会不知道打印哪个
}
}
class Demo_8_1
{
public static void main(String[] args)
{
Person p1= new Person(23,"Tom");
p1.showInfo();
System.out.println("Hello World!");
}
}
this属于一个对象,代表的是对象,其实就是一个对象的引用,只能在类定义的方法中使用。那么它代表那个对象呢?答:哪个对象调用了this所在的函数,this就代表那个对象。
this的使用之一:当成员变量和局部变量同名时,可以使用this来区分。
this的使用之二:使用this(参数列表)的方式就可以实现构造函数之间的调用。
注意:构造函数之间调用时,this语句只能定义在构造函数的第一行。