Categories
Uncategorized

Use Of this Keyword In Java: 2021 Guide

This guide will help you learn the uses of this keyword in Java.

In this guide, you will learn what this keyword is, how, and when to use it in Java.

So, without further delay, let dive deep into the topic.

Previous Topic: Java Class & Java Objects

Next Topic: Access Modifiers in Java

Page Contents

this Keyword in Java

this is a Java keyword. The this keyword in Java refers to the current object of a Java class. That’s all it means when you use the this keyword as it is.

If you add parenthesis ‘()’ to this keyword, it becomes the current class constructor call.

The keyword this is not alone, there is one more keyword similar to this in Java. i.e., the super keyword. The keywords this and super are the predefined object references in Java.

Note: You can learn about the super keyword in another upcoming guide. This guide talks about the uses of this keyword only. 

There are two roles of this keyword in Java.

  1. As the current object reference inside a class.
  2. As the class constructor call inside a constructor

I will explain it.

Let’s take the first use of this keyword in Java.

As The Current Object Reference

You can use this keyword inside a Java class to refer to the current object of the class. Current object means the object you use at the moment.

When you create an object of a class, if you want to use the reference of the object inside the class without passing the object reference to the class, you can use this keyword in Java.

When you write ‘this‘ in a Java class, you just referred to the current object. That’s it.

What you can do with object reference?

  • You can use the object reference to access the instance elements (instance variables, instance methods, etc) of the class
  • You can pass the object reference to a method or constructor as a parameter
  • You can return the object reference from methods

Well, you can do all the above with this keyword inside a Java class.

You can use this keyword in Java, just like you use a class reference variable.

Using reference variables, you can refer to objects inside the class or outside the class. You can create reference variables of your class in any other classes.

The only condition is that your class must be visible/available there.

But using this keyword, you can refer to the object within the class only.

Why?

Because that’s the purpose of it.

Imagine you create an object and assign it to a reference variable outside your class. Now you have one object, and your reference variable has the object’s reference.

If you use this object to access the instance variables or to call the instance methods, then this object is your current object at the moment. Right?

Now you want to use this current object’s reference inside your class. You can do that by sending the object reference to your class using a method, for example.

But there are places where you cannot pass the object’s reference to the class using a reference variable.

Where?

Inside the constructor of the class.

The constructor of a Java class is the one who creates the Java objects. Right?

To get and assign the object’s reference to a reference variable, first, the execution of the constructor must be completed.

Only then, you can make use of the object’s reference with a reference variable.

What if you need to use the reference of the object you are creating now inside the constructor before the constructor execution is completed?

Here you have only one option, this keyword in Java.

I hope you got it.!

If not, I suggest you read it once more and check out the below program as well.

public class Geeky {
	public Geeky() {
		System.out.println("Using this keyword: " + this);
	}

	public static void main(String[] args) {
		Geeky objectRef = new Geeky();
		System.out.println("Using reference variable: " + objectRef);
	}
}

OUTPUT:

Using this keyword: Geeky@372f7a8d
Using reference variable: Geeky@372f7a8d

In this program, we have a class named “Geeky” (I like the name. Please don’t judge me).

In the class, there is the Java main method and a constructor.

Inside the main method, I call the constructor to create the object of the class (new Geeky();) and assign the object reference to the reference variable “objectRef” (Geeky objectRef =) in the first line.

In the next line, I print the object reference stored in the variable “objectRef” using the “println()” method.

Inside the constructor, I use the “println()” method to print the object reference using this keyword.

When this program runs, JVM will execute the main method.

The first line inside the main method is the constructor call.

So, the constructor call will happen, and JVM will create the object.

You don’t see any object-creation program-statements inside the constructor because JVM does the creation of the object.

So, by the time JVM executes the “println() method call“, you see inside the constructor, the object will be created, and this keyword will have the object reference.

Therefore, the object reference in this keyword will be printed in the console as you see in the output above.

Next, JVM executes the second statement inside the main method, which is to print the object reference using the reference variable.

Both the reference variable and the this keyword show the same output.

Why?

Because both have the reference of the same object.

The object reference printed in the console is this: Geeky@372f7a8d.

Let’s break this into three parts.

  1. Geeky:- Class name
  2. @:- @ symbol
  3. 372f7a8d:- What is this?

To explain this first, we need to know about the hash code in Java.

Hash code is a unique int value associate with each object. Hash code makes objects unique in Java.

Hash code is generated by the JVM.

But 372f7a8d is not the hash code because it is not an int value. Right?

Yes. 372f7a8d is not an int value. It is the hexadecimal representation of the hash code.

By default, this is the format you will see while printing the object reference in the console in Java.

You can define your own format for object references in Java, which you can learn later here.

Now you know that you can use the object’s reference inside a constructor with this keyword in Java.

But.!

What is the need of using the current object’s reference inside the class?

It is simple.

To refer to the instance fields of the class inside the constructor or methods.

In the normal case, you can directly access the instance fields within the class.

The need for using the object reference occurs when the instance field name and the parameter name are the same.

This can happen with constructors and methods.
Here you can see that the instance field name and the constructor parameter name are the same.

The constructor is empty here. Let’s assign the value of the parameter “age” to the instance variable “age”.
The above program has no effect.

Why?

Because we are assigning the parameter “age” to itself, not to the instance variable “age“.

Assigning a variable to itself has no effect. Right?

The parameter “age” shadows the instance variable “age“.

When you write “age” inside the constructor as above, Java takes the parameter “age” because it is closer than the instance variable.

Java always takes the closer one.

This code won’t give you an error. If you are using an IDE like eclipse to create and run this program, you will get a warning that says “The assignment to variable age has no effect“.

Here you want to specify that the left-hand side of the statement “age =” is the instance variable.

The same is the case for methods or any other blocks in Java.

If there is a local variable in a method and there is an instance variable in the class with the same name, Java takes the local variable when you directly refer to the variable inside the method.

If you want to use the instance variable in the method in this case, you must mention that explicitly.

How do you do that in Java?

Using this keyword.

This is the most valid and most common reason to use this keyword in Java.

public class Geeky {
	int age;

	public Geeky(int age) {
		this.age = age;
	}

	public static void main(String[] args) {
		Geeky geekyObj = new Geeky(27);
		System.out.println("Age of Geeky " + geekyObj.age);
	}
}

OUTPUT:

Age of Geeky 27

An example of using this keyword inside a method is below.

public class Geeky {
	int age;

	/*
	 * Method to set the age of Geeky
	 */
	public void setAge(int age) {
		this.age = age;
	}

	public static void main(String[] args) {
		Geeky geekyObj = new Geeky();
		geekyObj.setAge(27);
		System.out.println("Age of Geeky " + geekyObj.age);
	}
}

OUTPUT:

Age of Geeky 27

You can use this keyword in Java as the method parameter value and also as the return value of a method.

Using this keyword as the method parameter value

public class Geeky {

	public Geeky() {
		/*
		 * calls the printObjReference() method inside the constructor and pass the
		 * object reference using this
		 */
		printObjReference(this);
	}

	/*
	 * Method that accepts the object reference as parameter and prints it on the
	 * console
	 */
	public void printObjReference(Geeky reference) {
		System.out.println(reference);
	}

	public static void main(String[] args) {
		Geeky geekyObj = new Geeky();
	}
}

OUTPUT:

Geeky@372f7a8d

Using this keyword as the constructor parameter value

public class Geeky {
	/*
	 * Default Constructor
	 */
	public Geeky() {}

	/*
	 * Constructor with class object reference as parameter
	 */
	public Geeky(Geeky firstObject) {
		/* Prints the first object reference in the console */
		System.out.println("First Object: " + firstObject);
	}

	public void passObjReference() {
		/*
		 * Creates the second object using the 
		 * parametrised constructor and pass the
		 * current object reference using this keyword
		 */
		Geeky secondObject = new Geeky(this);
		/* Prints the second object reference in the console */
		System.out.println("Second Object: " + secondObject);
	}
	public static void main(String[] args) {
		/*
		 * Creates the first object using the default constructor 
		 * and calls the instance method passObjReference()
		 */
		Geeky firstObject = new Geeky();
		firstObject.passObjReference();
	}
}

OUTPUT:

First Object: Geeky@15db9742
Second Object: Geeky@6d06d69c

Using this keyword as the return value of a method

public class Geeky {
	/*
	 * Method that returns the current object reference using this keyword
	 */
	public Geeky returnThis() {
		return this;
	}

	public static void main(String[] args) {
		/*
		 * Creates the Geeky Class Object by calling the Constructor and calls
		 * returnThis() method 
		 * 
		 * (This code is just to show you the use of this keyword as the
		 * return value of a method. 
		 * 
		 * You don't have to do like this to get the object
		 * reference. The Constructor call is enough)
		 */
		Geeky geeky = new Geeky().returnThis();

		/*
		 * Prints the object reference returned from the method
		 */
		System.out.println(geeky);
	}
}

OUTPUT:

Geeky@372f7a8d

Another important thing to note is that you can’t use this keyword inside a static context/block.

public class Geeky {

	static {
		System.out.println(this); // this keyword inside static block - Invalid
	}

	public static void main(String[] args) {
		System.out.println(this); // this keyword inside static method - Invalid
	}

}

Here you can see that inside the class there is a static block and the static method main. Inside both, I try to print the object reference using this keyword. Both are invalid.

If you try to use this keyword inside a static context like above, you will end up getting an error that says “Cannot use this in a static context“.

This is because static blocks/methods belong to a class, not to the objects of a class. Static blocks will be executed after the class is loaded. There won’t be any object created at that time.

In the case of the static method, you can access them using the class name.

The use of this keyword in Java comes into effect only after an object is created. So there is no point in using this keyword inside a static block or static methods.

You can read this related topic to learn a little more.

As The Class Constructor Call

If you add parentheses to this keyword, it acts as a constructor call.

this() is used to call a constructor of a class from another constructor of the same class.

Another constructor?

Can we have multiple constructors for a Java class?

Yes. In Java, you can create n number of constructors for a class. This is called constructor overloading.

The only condition when you overload constructors is that the signature of the constructors must be different.

For example, the default constructor has no parameters. If you have added the default constructor to your Java class, then there should not be another constructor with no parameters.

You can make different constructors by changing the type or number of the parameters different. For example, you can have a constructor with an int parameter and another one with a float parameter or two int parameters.

public class Geeky {
	public Geeky() {
		System.out.println("default constructor (no parameters)");
	}

	public Geeky(String name) {
                this(); //calling the default constructor
		System.out.println("constructor with a string parameter");
	}
}

In this program, the Geeky class has two constructors

  1. The default constructor (constructor with no parameters)
  2. Constructor with one parameter (parameter “name”)

In the above program, I call the default constructor from the second constructor using this(). This is how you can call a constructor from another constructor of the same class.

You can use this() call to pass parameters from one constructor to another while creating the object.

public class Geeky {

	String name;
	int age;

	public Geeky() {
		System.out.println("default constructor: " + this);
	}

	public Geeky(String name) {
		this();
		this.name = name;
		System.out.println("constructor with parameter name: " + this);
	}

	public Geeky(String name, int age) {
		this(name);
		this.age = age;
		System.out.println("constructor with parameter name and age: " + this);
	}

	public static void main(String[] args) {
		Geeky geekyObj = new Geeky("geeky", 27);
	}
}

In this program, we have three constructors of the class Geeky.

  1. The default constructor
  2. Constructor with one parameter (parameter “name”)
  3. Constructor with two parameters (parameter “name” and “age”)

When you run the program, the main method will be executed first.

Inside the main method, we call the constructor that has two parameters to create the object of the Geeky class. So we pass the name and age to the constructor.

Inside the two-parameter constructor, in the first line, we call the constructor that has one parameter and pass the name. So the control goes to the one-parameter constructor.

Again, inside the one-parameter constructor, in the first line, we call the default constructor. So, now the control goes to the default constructor.

Inside the default constructor, we print the current object reference using this keyword.

So, we get the output of the println() method as below.

default constructor: Geeky@15db9742

After the execution of this, the control returns to the one-parameter constructor.

In the second line of the one-parameter constructor, we assign the parameter “name” to the instance field “name”, and in the third line, we print the current object reference using this keyword.

Here we get the output of the println() method as below.

constructor with parameter name: Geeky@15db9742

Next, the control returns to the two-parameter constructor.

Here, in the second line, we assign the parameter “age” to the instance field “age”, and in the third line, we print the current object reference using this keyword.

constructor with parameter name and age: Geeky@15db9742

Finally, the program control returns to the main method and the reference of the object is assigned to the reference variable “geekyObj”.

In all the print statements above, you can see that the object reference printed using this keyword is the same.

This is because by using this() as the current class constructor call, multiple objects won’t be created.

The actual use of this() call is to make use of one constructor from another of the same class, not to create multiple objects.

Calling one constructor from another makes a chain of constructor call. We call this constructor chaining.

As you see in the above program, you can use this constructor chaining to divide and write the assignment of instance fields in multiple constructors in Java.

In the above program, we assign the value of parameter “age” to the instance field “age” in the two-parameter constructor.

public Geeky(String name, int age) {
this(name);
this.age = age;
System.out.println(“constructor with parameter name and age: ” + this);
}

But the value of the parameter “name” is assigned to the field “name” inside the one-parameter constructor using constructor chaining.

I hope you understood.

There are three important points to note here:

1. You can’t use this() outside a constructor

The purpose of this() is to create constructor chaining. So it must always be inside a constructor.

2. The this() constructor call must be always in the first line of a constructor

You can’t use this() as the second or third program statement inside a constructor. It must always be in the first line. If not, you will get an error.

Why?

Because, first, the object must be created, before anything you wish to do inside a constructor. Right? That’s why.

If you add this() inside one of your constructors, the object is created after the constructor called using this() is executed, not before that.

Hence, the this() call must always be in the first line of a constructor, if you wish to use it.

3. You can’t use this() to call the same constructor. 

In Java, you can’t make the same constructor call using this(). Java prevents it. It should always be another constructor.

Why?

Because it will cause recursion.

public class Geeky {

	public Geeky() {
		this(); // Recursive constructor invocation Geeky() - Invalid
	}
}

Conclusion

This guide discusses the “this keyword in Java”. I explained what this keyword is and the various uses of the keyword.

I hope you got some practical, useful information from this guide.

If you find this guide useful, consider dropping a quick comment.

Also, share it with your friends to spread some knowledge.

I will meet you in the next post soon.!

Leave a Reply

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