This Java Keyword | Using This in Java Constructor and Method

I remember myself to be confused on numerous occasions, trying to understand what this java keyword is all about and how to use ‘this’ in Java. Could be owing to its weird misplacement and it being insanely aloof to what ‘this’ should actually mean when you are talking general slang.

Surprisingly ‘this’ is a lot much easier than it actually might seem. Now that we are already properly introduced to use of constructors and methods, understanding this java keyword would be like a walk in the park.

let's do this nicolas cage meme

What is This?

Lol! Almost sounds like you are pointing. Okay, this java keyword is nothing but a reference variable just like super keyword that we had seen in the previous chapter.

This points to the ‘current object’. Yes, it is the object whose method or constructor is being called. We often use it to get rid of ambiguity. So, if there are naming conflicts entailed and your compiler doesn’t understand which variable is being called, using this comes handy.

Why this is used in Java?

You can achieve the following things with the aid of using this java keyword:

  • It can be used to refer to current instance variable
  • You can use this to invoke current class constructor
  • Can be used to invoke current class method
  • It can be flung around as an argument in a method call
  • Can be used as an argument in a constructor call too
  • This can be used to return current class instance from method

One by one we shall see how we can use this to refer and invoke various stuff:

Referring Current Instance Variable

I am gonna take a parameterized scenario into account in order to understand this. Let’s just say we have two parameters for a constructor.

You a friends fanatic? You are going to love this example.

Let’s say we have a class called Joey. There are two instance variables that have been initiated to some value. They have been defined locally with the same name as parameters as shown:

parameters of a constructor same name

We will create a method called display so that it would aid us in displaying values inside those fields.

Using main method now to create an instance and then call display():

example for when you do not use this

On running the above program you will see that the result for instance variable has been displayed as is. Why didn’t it take local variable into account?

It’s because of the ambiguity.

The following code:

quote = quote;
age = age;

had no effect. And it was skipped big time.

To make sure it should have been taken into consideration, we can either use different variables in lieu of quote and age on the R.H.S. and replace it in the constructor parameter as well like:

Joey(String x, int y) {

          quote = x;
          age = y;

}

But to avoid extra rework we can simply use *drum rolls* – the this java keyword. Simply replace the above code with:

this.quote = quote;
this.age = age;

and now run the program:

result with this java keyword

See? The difference? Both the parameters have now been replaced with the inputs we have provided.

The Implicit Call of This Java Keyword

This Java keyword is also implicitly called in case you are using different argument names. In the example above where we were trying to scooch in x and y variables as arguments:

Joey(String x, int y) {

          quote = x;
          age = y;

}

this gets called implicitly. So the above means in fact:

Joey(String x, int y) {

this.quote = x;
this.age = y;

}

When there are two objects involved the compiler simply replaces the this Java keyword with the instance, you are using to call the constructor.

Invoking Current Class Constructor (Constructor Chaining)

Did you know “this java” keyword can also be used to reuse constructors? This process is also known as constructor chaining.

So you can call a default constructor from a parameterized constructor and vice versa. We will see an example that will make things clear.

Let’s get rid of all the methods for a sec in our example. Let’s display something in our default constructor. Then create a parameterized constructor to invoke current class constructor.

image-to-use-this-in-constructors

Notice how the parameterized constructor uses this() to supposedly call the default constructor? Let’s run this program by putting a main method in the equation, and see if the messages get displayed in order.

result for invoking current class constructor

Result gets displayed fine.

We will see if it works the other way around, I mean calling a parameterized constructor from a default constructor:

invoking a parameterized constructor from default constructor example

Did you know in case of inheritance, we could increase the length of the chain with super as well? Try that yourself and let me know how things fair.

NOTE: Just like super() call to this() should be the first statement in constructor. Don’t worry you will get a compile-time error if you are using the Eclipse IDE.

Invoking Current Class Method

Since Constructor is a type of method, things are going to be fairly simple here I assume.

Create two different methods with the second one using this.firstMethod() in its declaration like this:

two methods in class

Now the time has come to include main method where we will create a class instance and then force it to call Monica() method.

Since, the method Ross() is called using this keyword “Unagi” should be displayed later.

Here’s the update and run:

result when we call method using this

Here you could choose to remove “this” keyword since it makes an implicit call anyhow. So using just

Ross();

would also get you the same result.

Passing This as an Argument in Method

Yes, this can also be passed as an argument. I know right? Mind = Explode.

Since we used to use only primitive data types like String, int, float etc. in the arguments, it is a tad hard to digest that a reference data type can also be passed as an argument. Such a scenario is often used in Event Handling, something we will see at a later stage.

We will see a lil example of the above case first, and then get back on passing ‘this’ as an argument in method. Then we will see how to use this java keyword as an argument in a constructor as well.

So creating a scenario where we will use an object to be passed as an argument:

program to show object to be passed as an argument

Notice how we have simply mentioned an instance named as Joey k and passed it as an argument? While calling the method now we have to make sure an instance is passed, and so we can enter the method.

If you run the above program you will get the result as:

I am Joey's Apple.

Now checking if we could pass this as an argument here. We will create another method:

when you call this as an argument

Here we have created another method Phoebe() and used this as an argument inside the Ross() method. Remember this is implicitly being called as well. So Ross(this) in fact means:

this.Ross(this);

We are calling the Ross() method using this argument and then displaying what the method has to say. Then we are printing the remaining statement inside our initially called method Phoebe().

Here’s the result we will get:

I am Joey's Apple.
I am Princess Consuela Banana Hammock.

Now let’s move on to see how easy it is in case of constructors.

Passing this as an argument in Constructor

Yes this java keyword can also be passed as an argument in a Constructor. To see that happen we will create a separate class known as Chandler.

an example of Chandler class with objects

The reason we have created a Joey instance here is because we want to use ‘this’ as a constructor argument. So hereby we have created a Chandler constructor and passed Joey’s instance to it, so that if we call Chandler using its constructor we can use ‘this’ there.

Now moving on to our Joey class where the main method is there. We will simply use it to call the constructor of Joey.

using Joey class to pass this as constructor argument

You might argue why didn’t we use ‘this’ directly instead of creating a chain from Joey’s constructor to Chandler’s? Well to answer that I will say it will give a compile time error if you do that since ‘this’ cannot be used in static context.

Now we have called Joey’s constructor to call Chandler’s and used ‘this’ in the arguments to refer to Joey’s object that will be used in Chandler class. I am sure real life Joey and Chandler wouldn’t mind this weird farrago.

Run the program and see how we are jumping from one constructor to another. Both the messages will be displayed in correct order. You will get the following result:

I am in Chandler now.
I am back in Joey now.

Now time to see what else it could do.

Returning Current Class Instance

This can also be used to be returned as a statement to a method. The only way to do it is by ensuring the return type of the method must be a non-primitive data type.

The syntax to follow here is:

return this;

That is all.

example to return this in a method in Java

Notice calling method() is going to provide us the instance back, which we have used to call display.

You will get the following result:

What's going on?

Oh! well everything’s fine. How about you? 😛

This concludes this. We will see more of this when we start using it in our actual programs.

Scottshak

Poet. Author. Blogger. Screenwriter. Director. Editor. Software Engineer. Author of "Songs of a Ruin" and proud owner of four websites and two production houses. Also, one of the geekiest Test Automation Engineers based in Ahmedabad.

You may also like...

Leave a Reply