Learn Pain Less

HomeOur TeamContact
Java
What is the use of this keyword in JAVA
Pawneshwer Gupta
Pawneshwer Gupta
March 22, 2015
1 min

Table Of Contents

01
This keyword in java
02
Using this to disambiguate variable references.
03
Using this as an argument passed to another object.
04
Using this to call alternate constructors.
What is the use of this keyword in JAVA

This keyword in java

The this keyword is primarily used in three situations. The first and most common is in setter methods to disambiguate variable references. The second is when there is a need to pass the current class instance as an argument to a method of another object. The third is as a way to call alternate constructors from within a constructor.

Case 1:

Using this to disambiguate variable references.

In Java setter methods, we commonly pass in an argument with the same name as the private member variable we are attempting to set. We then assign the argument x to this.x. This makes it clear that you are assigning the value of the parameter “name” to the instance variable “name”.

public class Foo
{
private String name;
public void setName(String name) {
this.name = name;
}
}

Case 2:

Using this as an argument passed to another object.

public class Foo
{
public String useBarMethod() {
Bar theBar = new Bar();
return theBar.barMethod(this);
}
public String getName() {
return "Foo";
}
}
public class Bar
{
public void barMethod(Foo obj) {
obj.getName();
}
}

Case 3:

Using this to call alternate constructors.

When you have multiple constructors for a single class, you can use this(arg0, arg1, …) to call another constructor of your choosing, provided you do so in the first line of your constructor.

class Foo
{
public Foo() {
this("Some default value for bar");
//optional other lines
}
public Foo(String bar) {
// Do something with bar
}
}

I have also seen this used to emphasize the fact that an instance variable is being referenced (sans the need for disambiguation), but that is a rare case in my opinion.

Source : https://stackoverflow.com/a/2411283/5231773

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Tags

startthis keywordjava tutorial

Share


Pawneshwer Gupta

Pawneshwer Gupta

Software Developer

Pawneshwer Gupta works as a software engineer who is enthusiastic in creating efficient and innovative software solutions.

Expertise

Python
Flutter
Laravel
NodeJS

Social Media

Related Posts

Working with Files, Folders java
Working with Files, Folders java
March 25, 2015
1 min
Learn Pain Less  © 2024, All Rights Reserved.
Crafted with by Prolong Services

Quick Links

Advertise with usAbout UsContact Us

Social Media