This Keyword in Java

"This" keyword in java is one of the most used and very important keywords.
"This" keyword in java is used to refer current class objects.
We can use this keyword to access current class object members.

Image of boy for understanding this keyword in java

So you might be wondering if we can access the current class member directly, Why do we need this keyword?

One of the answer is that, if we have same name for method level and class level variable, then there is an ambiguity for JVM. JVM can not use class variable and uses the local variable by default. In such a case we can use "this" keyword for referring the class level variable.

6 uses of "this" keyword in java

  1. Accessing class level variable
  2. Accessing class methods - default
  3. For calling other constructor of same class
  4. Using 'this' keyword as return value
  5. Passing 'this' keyword as argument to method
  6. Passing this keyword as argument to constructor

1. Accessing class level variable

Assessing class level variable using this keyword is the most common use of "this" keyword.

Syntax: this.variableName

Most of the time we create some variable in class, then we can set the value from constructor or setter method. If we use same name for argument variable and class level variable then jvm will use local variable always, and it will not set the value to class level variable

lets take a look at example for better understanding,

public class Country{
private String name;
public Country(String name){
Wrong: name = name;
Right: this.name = name;
}
}

As shown in the above example if we just use name =name, value from argument will not be assigned to the class level variable. So the class level variable will always be null. This is because we set value to same variable not the class level variable.

The correct solution is to use this.name = name;

2. Accessing class methods using "this" keyword

For calling the same class method we can use this keyword.

However using this keyword for calling same class method is optional. Because even if you don't use this keyword, jvm always calls the method from same class by default.

Syntax: this.methodName(arguments);

Following examples shows two cases of calling class method with and without this keyword. In both cases the same method is called.

public class Dog{
	public void testMethod(String[] args){
		printString();
		this.printString();
	}	
	public void printString(){
		System.out.println("Success);
	}
}

Output:

Success
Success

3. For calling other constructor of same class

"This" keyword in java can be used to call other constructor of same class.

Some times we have different constructors with different parameters then you can reuse existing constructor using "this" keyword.
We can call any type of constructor within any constructor. That is we can call default in parameterized, parameterized in defatul or parameterized in parameterized constructor.

Syntax: this() or this(args)

The most important thing to note is that the use of "this" for calling other constructor should be the first line in constructor.

Let's assume we have a class, let's call it SomeClass. In this class we have a default constructor and a constructor with variable.
There is some default code that is required for at object creation. So we have added this code in default constructor.
Now we need the same code from default constructor in parameterized constructor. So in this case we can call default constructor from another constructor using this();

public class SomeClass{
	private int variable ;

	public SomeClass(){
		// some code...
	}
	public SomeClass(int variable ){
		this()
		this.variable = variable ;
	}
}

Lets take look at real life examples for shape class. In this class we have length and breadth variables. we need two constructors.
Fist constructor will take two arguments for length and breadth.
Second constructor will take only one argument, this will be same value for length and breath.

public class Shape{
	private int length ;
	private int breadth;

	public Shape(int length ,int breadth){
		this.length = length ;
		this.breadth = breadth;
	}

	public Shape(int length ){
		this(length,length);
	}
}

In above examples we are reusing constructors using "this" keyword in java.

4. Using "this" keyword as return value in java

If you need to return current object instance we can use "this" keyword.
Builder design pattern is one of the most common example of this case.

Let's look at an example for better understanding,

public class MenuBuilder{
	List<Menu> menus = new ArrayList<>();

	public MenuBuilder withAdd(){
		menus.add(new Menus("Add"))
		 return this;
	}
}

As you can see in the above example, we used "this" as return value in withAdd() Method. In above example withAdd() method returns the current class object.

5. Passing "this" keyword as argument to method

If we want to call some method and the method needs current class object as argument, we can use this keyword to pass the current class object instance.

We can pass this as argument to current class as well as another class methods.

public class City{
	private String name;
	private Country country;
	
	public City(String name){
		this.name= name;		
	}
	public void setCountry(Country country){
		this.country = country;		
	}
}
public class Country{
	private City capital;
	
	public void setCapital(String cityName){
		City capital = new City(cityName);

	// passing country class object using this keyword
		capital.setCountry(this);
		this.capital = capital;		
	}
}

As shown in the above example, we have City and Country class. In City class setCountry() method needs object of Country class. So we have passed Country class instance using "this" keyword from Country class.

6. Passing "this" keyword as argument to constructor

Similar to passing as argument to another method we can also pass "this" keyword as argument to constructor of another class.

We can pass this as argument to constructor of current class as well as to constructor of another class.

public class City{
	private String name;
	private Country country;
	
	public City(String name, Country country){
		this.name= name;		
		this.country = country;		
	}
}
public class Country{
	private City capital;
	
	public void setCapital(String cityName){
	// passing country class object using this keyword
		City capital = new City(cityName,this);
		this.capital = capital;	
	}
}

As shown in the above example, we have City and Country class. In City class constructor needs object of Country class. So we have passed Country class instance using "this" keyword from Country class.

Fast track reading

  • This keyword in java is used to refer current class objects
  • Using this keyword we can access current class instance variable, methods, or constructor
  • We can pass this keyword as argument to another method or constructor
  • We can return current class instance using this keyword

Related topics

Leave a Reply

Your email address will not be published. Required fields are marked *