this
is one of the java
keywords and it helps in referring to the current object. When we use the dot(
.
) operator on
this
keyword, then we can access the member variables of the current object.
this
keyword can also be used to call one constructor from another constructors of the same class.
The parameter names passed to the constructors can have the same name as the member variables of that class.
For
e.g., the constructor with parameters
nameParam
,
marksParam
and
sectionParam
class Student
{
String name;
int marks;
char section;
Student(String nameParam, int marksParam, char sectionParam)
{
name = nameParam;
marks = marksParam;
section = sectionParam;
}
}
can be rewritten as
Student(String name, int marks, char section)
{
this.name = name;
this.marks = marks;
this.section = section;
}
If we have the parameter name same as the member variable, then the parameter hides the member variable. That is even if we assign value to the parameter, then the member variable is not affected. We can use the
this
keyword to distinguish the member variable
name
from the parameter
name
. When
this.name
is called it is the member variable, and when only
name
is called it is the parameter. Similarly,
this.marks
and
this.section
are member variables, where as
marks
and
section
are parameters.
The other use this keyword is to call the same class constructors. For
e.g., the following code
// CONSTRUCTOR 1
Student(String nameParam, int marksParam, char sectionParam)
{
name = nameParam;
marks = marksParam;
section = sectionParam;
}
// CONSTRUCTOR 2
Student(String nameParam, int marksParam)
{
name = nameParam;
marks = marksParam;
section = 'A';
}
// CONSTRUCTOR 3
Student(String nameParam)
{
name = nameParam;
marks = 0;
section = 'A';
}
can be rewritten as
// CONSTRUCTOR 1
Student(String name, int marks, char section)
{
this.name = name;
this.marks = marks;
this.section = section;
}
// CONSTRUCTOR 2
Student(String name, int marks)
{
this(name, marks, 'A');
}
// CONSTRUCTOR 3
Student(String name)
{
this(name, 0, 'A');
}
Here we have used
this
keyword, both to distinguish (or identify) the member variables from the parameters and also to call the same class constructor.
- In
CONSTRUCTOR 1
, we have initialized the member variables this.name
, this.marks
and this.section
with parameters name
, marks
and section
.
- In
CONSTRUCTOR 2
, we are calling the CONSTRUCTOR 1
using this keyword
.
- Similarly, in
CONSTRUCTOR 3
also, we are calling the CONSTRUCTOR 1
using this
keyword.