Re: What does a "this" reference do?

you see in the code above I created an int variable called "num1" and also in the constructor I take an int argument also called num1. lets say whichever value the constructor gets from its argument it should assign it to the num1 variable I created in the class, if I had not put the "this" keyword the compiler would be confused as to which num i'm referring to. Because both class variable and the constructor argument have the same name.

So when I put the this keyword, i'm letting the compiler know that I am referring the "num1" variable that I created in the class and not the "num1" variable that's in the constructor argument.

If you don't want to use the this keyword then all you would have to do is give different variable names that doesn't conflict with the ones that are given in a parameter of a constructor or a method here's an example of writing the same code above but without using the "this" keyword

In this case, there are two instances of Test created in TestRunner. At this line

Test test1 = new Test(3);

we call the constructor. When that constructor runs, "this" refers to the object we've named as "test1". In the second line, when the constructor runs, "this" refers to the object we're calling test2.

You can test this by creating this class and giving it a getter method to get the num1 object.

test1.getNum1();

will return 3

and

test2.getNum1();

will return 7.

More clear now?

EDIT: Musing on this, I find that "this" is a little bit deceptive because what it generally means is somewhat the opposite of our normal English usage. In normal English, "this" means "the one nearest to hand". "This apple" is the one I have in my hand, "that apple" is the one over there on the table. Now, in Java, the one nearest to hand is the one you use automatically, so "this" means actually "not the one here in my hand". That's awkward! Fortunately, it's a confusion that you're not going to run into because by the time you understand that you ought to be confused by it, you understand it.

In Dankwansere's example quoted above, there are two things called num1 in the the Test class. One is a field of the class, and it persists with the object as long as the object persists. The one declared within the constructor (as an argument to the constructor, but it's lexically within the constructor) is a completely different object, and it only exists as long as the constructor is running. Nobody else can ever look at that particular entity.
When he says this.num1=num1, he means "the num1 that pertains to the current oject (not the one in the current scope) is to be set equal to the num1 that is in the current scope".

This may clear things up, or it may confuse you more. It's true all the same.