r/javahelp • • Apr 25 '16

Quick complaint about this. keyword.

Is it just me or is this. the most counter intuitive keyword in java. When I see this. I think about THIS variable when in reality I am referring to THAT variable that is class level. End of complaint.

1 Upvotes

5 comments sorted by

3

u/Tuwiuu Apr 25 '16 edited Apr 25 '16

"this" doesn't represent the class variable, it represents an instance of the class you're using it in. It's in line with how you access public variables of a class, as in foo.bar if bar was a public variable of the Foo class and foo was an instance of the Foo class.

Inside the Foo class you would use it with this.bar

Maybe it seems a little more intuitive now?

1

u/[deleted] Apr 25 '16

Say I have a dog class. And in that dog class I have two public variables, a variable for age and a variable for name.

I create an instance called mydog.

I would access those variables by typing in:

mydog.age or mydog.name

Basically "mydog" is just a memory address and at that memory address is the start of an instance of the Dog class.

"this" refers to the same memory location as the mydog variable, or any Dog object that uses it.

Hope this helps.

1

u/Targom Apr 25 '16

I don't think you should really be using the same variable name for something that is class level and something that is method specific. Having tutored people at my school, I often advise them to name the variables different as they are passed into a method since some of them have a hard time differentiating between the scope of the variables.

2

u/Sacredify Apr 25 '16

Theres really one real use for shadowing - setter method parameter names - easier to use the variable name than come up with something else:

public void setFoo(int foo) {  this.foo = foo; } 

best avoided really anywhere else.

1

u/Philboyd_Studge Apr 25 '16

You don't have to use it.