The this keyword eliminates the need to have unique variable names for constructors.
Oftentimes, you already named a variable well and to have a unique name for the constructor, you would either have to come up with a new name or otherwise mar the good one you have.
In addition, it allows you to name local variables and instance variables the same and have a way to use the one you wish.
For example:
public class Foo
{
//instance variable
private String myVar;
public Foo(String myVar)
{
this.myVar = myVar;
}
public void someFunc()
{
String myVar = "Hello";// local variable
this.myVar = "World";//instance variable
Console.WriteLine(myVar + this.myVar);//prints HelloWorld
}
}
In C++ ‘this’ is a pointer, so you would need to reference members using the ‘->’ operator.
solved what is the equivalent reference for “this” in C/C [closed]