What is this Keyword in Java?
Java is an object-oriented language and there can be many objects present at a time, on those we could be operating, “this” keyword here comes in the picture because it helps to point the current instance or current object of a class.
Hence when we look to invoke methods of the current class, when we want to invoke the constructor of the current class, return the current instance from methods, pass the current instance to methods; in all these instances this keyword comes handy.
Example use-cases
- Synchronized block in multithreading uses this keyword as an argument
- Constructor overloading
Why to Use this Keyword in Java?
- ‘this’ variable acts as a final variable in java i.e. we cannot assign any value to ‘this’ variable, this can be cross-checked by assigning a value to ‘this’ keyword and it will lead to a compilation error.
- ‘this’ can be used to refer static members too ( but it shall not be done) because static members are declared once only i.e. the memory allocation done to them is once only and if we try to make manipulations using ‘this’ keyword then it will always manipulate the data placed at that memory location rather than creating data at new memory locations, which objects do.
- This prevents the task of making unnecessary assignments to variables and at times we need not create extra variables too, ‘this’ keyword wherever used gives us the surety that the current instance is being referred to.
Importance of this Keyword
The below examples show that we need to create variables with different names for particular properties, they can simply be assigned in constructor during object initialization using this keyword.
- Prevents member variable and local variable name conflict, one can refer the member variable using this keyword.
public class Student {
int marks;
String subjectName;
//constructor
public Student(int marks, String subjectName)
{
this.marks = marks;
this.subjectName=subjectName;
}
public Student()
{
}
public static void main(String args[])
{
Student s = new Student(1,"name");
}
}
- Methods of object class also can be invoked using this.
//consider a method shown here
public String getName()
{
return this.toString();
}
- This can be used in setter and getter methods, to return the current instances.
Public int getmarks()
{
return this.marks;
}
public void setMarks(int marks)
{
this.marks =marks;
}
4.8 (8,018 ratings)
View Course
Particular Uses of this Keyword
Here are some uses of this keyword explained below with implementation:
1. Use With-in a Field
public class PointCoordinates {
public int xval = 0;
public int yval = 0;
//constructor
public PointCoordinates (int a, int b) {
xval = a;
yval = b;
}
public static void main(String args[])
{
}
}
But it could have been written like this:
public class PointCoordinates {
public int xval = 0;
public int yval= 0;
//constructor
public PointCoordinates (int xval, int yval) {
this.xval = xval;
this.yval = yval;
}
public static void main(String args[])
{
}
}
So this was something we explained in the last section also, where it can be seen that the naming conventions for one kind of data field can be kept uniform if we are using the ‘this’ keyword.
Hence a developer is not supposed to keep track or mapping a chart of variables for the same kind of logical data field.
2. Constructor Invocation Using this Keyword
We can use this keyword inside a constructor and call another constructor from there, in the same class. This is also called explicit constructor invocation.
Let’s consider an example shows below for the same –
public class Square {
private int x;
private int side;
public Square () {
this(1);
}
public Square (int side) {
this(0, side);
}
public Square (int x, int side) {
this.x = x;
this.side = side;
}
public static void main(String args[])
{
}
}
There are three constructors here in the picture, note that the default constructor is supposed to be placed explicitly when we are doing constructor overloading.
These constructors are initializing some member variables, the compiler is getting an indication here about constructor invocation via the number of parameters used inside the methods.
3. Returning Current Class Instance Using this Keyword
class Rectangle
{
int height;
int width;
Rectangle()
{
height = 10;
width = 20;
}
//Method to return current class instance
Rectangle getObject()
{
return this;
}
public void print()
{
System.out.println(height+" , "+ width);
}
public static void main(String[] args)
{
Rectangle object = new Rectangle();
object.getObject().print();
}
}
So, in the example shown above, it can be seen that the current object is being returned from a getter method and on that instance, the particular method “print” has been invoked.
4. Use as Method Parameter
class Rectangle
{
int height;
int width;
Rectangle()
{
height = 10;
width = 20;
}
void getObject()
{
print(this);
}
public void print(Rectangle object)
{
System.out.println(object.height + " , " + object.width);
}
public static void main(String[] args)
{
Rectangle object = new Rectangle();
object.getObject();
}
}
The example cited how the current object is being passed to a method that can use this object for its custom use.
Conclusion
We saw various use cases here, citing the variants against usage of this keyword in java and where to use and where not to use, those conditions have been put up in an explicit manner.
‘this’ keyword is common among all the programming languages, in the javascript-based frameworks too, ‘this’ finds a key role.
‘this’ keyword can become overhead if not understood well and it is a great help for developers if understood properly.
Recommended Articles
This is a guide to this keyword in java. Here we discuss importance, particular uses, and examples of this keyword in java along with its code implementation. You may also look at the following articles to learn more-