Java- this 引用

this对象

this是一个对象,其中包含另一个调用成员函数的对象的引用。

程序:

import java.util.Scanner;
class ThisKeyword
{
	private int a;
	private int b;
	void getData(inta,int b)
	{
	a=a;
	b=b;
	}
	void showData()
	{
	System.out.println("Value of Variable A is:"+a);
	System.out.println("Value of Variable B is:"+b);
	}
}
class ThisKeywordExample
{
	public static void main(String args[])
	{
	ThisKeyword T=new ThisKeyword();
	T.getData(4,5);
	T.showData();
	}
}

输出结果

Value of Variable A is:0
Value of Variable B is:0

输出说明。

这是带有示例的Java

对于getData()方法主体,编译器是否应该优先考虑实例变量局部变量感到困惑,这就是为什么在showData()方法中,编译器优先考虑实例变量并提供等于零的输出。

我们可以通过在getData()方法中使用此引用变量来避免这种情况,如下所示:

this.a=a;
this.b=b;

当对象T调用该getData()方法时,此引用将替换为对象T的引用,从而:

T.a=a;
T.b=b;

因此,Ta是实例变量,而a是getData()方法参数中定义的局部变量。