在java中为了屏蔽指针,而又想避免程序的混乱,所以创建了this关键字。先看一个简单的例子:
class A
{
private int i = 2;
public A(int j)
{
i = j;
}
public void show() //如果在C语言中,相当于:public void show(A * this);
{
System.out.printf("i = %d\n", i); //如果在C语言中,相当于:System.out.printf("i = %d\n", this.i);
}
}
public class TestThis
{
public static void main(String[] args)
{
A aa1 = new A(10);
A aa2 = new A(20);
aa1.show(); //如果在C语言中,相当于:aa1.show(aa1);
aa2.show(); //如果在C语言中,相当于:aa2.show(aa2);
}
}
在上面程序中,
A aa1 = new A(10);
A aa2 = new A(20);
产生的作用图下图所示:
在创建两个不同新对象时,各个对象各自的属性(变量)成员占用不同的内存,而方法则是共用同一段内存,所以java使用this来避免混淆。this实质上是C语言中指针的用法,但在java中不用我们自己编写指针,一个系统隐含的指针会自动附加在非静态的成员函数参数列表上。
this有两种常用的用法:
1、在构造方法中,this代表当前时刻正在创建的对象
2、在普通方法中,this代表正在调用show方法的对象
class A
{
private int i = 2;
public A(int i)
{
this.i = i; //在构造方法中,this代表当前时刻正在创建的对象
}
public void show()
{
System.out.printf("i = %d\n", this.i); //在普通方法中,this代表正在调用show方法的对象
}
}
public class TestThis
{
public static void main(String[] args)
{
A aa = new A(99);
aa.show();
}
}