What is the purpose of THIS keyword .

Don’t get confused I’m talking not about that this but , about THIS this keyword .

Are we confused yet ? good , lets get started . Using the this keyword can allows us to have multiple constructors in the same class. how ?

well the keyword has a pointer to the object that it’s currently in. So , you can use the this keyword on non static methods or constructors

Let’s look at some code to paint a clear idea. ( The code will be available down at the bottom of the page where you will see the link of the program from my GitHub)

Cool ! , we have a class that contains 2 strings named a ,b . And it just so happens we have a constructors we the same names .

Now , this is exactly of those times you want to use this . Because we are specifying a field in a new variable, which have the same name .

So essentially , what we are doing is to specify that the variable that indeed does have the name is not a local variable , but an instance variable.

Output :

If we didn’t have the this keyword let’s see what happens :

ooops ! , our program doesn’t know what our intentions are. We have to write to it precise instructions .

https://github.com/ValorWind1/Java_Review_1.0/tree/master/src/java_youtubeclips/this_keywordd

Leave a comment