The this Keyword

this

Part of: Writing Classes

What this Refers To. Inside an instance method or constructor, this is a reference to the object the method was called on . When you write d.speak(), inside speak() the keyword this refers to the same object d points to. It lets an object talk about itself. Resolving Name Conflicts. The most common use of this is to fix a naming clash. A constructor parameter and an instance variable often share a name for readability. Without this, the parameter shadows the field: Using this makes the left side mean the field and the right side the parameter : Passing the Current Object. Because this is a reference to the current object, you can pass it to other methods or return it: Returning this lets calls be chained: acct.deposit(10).deposit(5). When You Can Omit this. If there is no name conflict, this is optional. These two lines do the same thing inside a method: What usually goes wrong. What you see What caused it How to fix it --- --- --- Every computed result comes back as 0 x = x assigned the parameter to itself, so the field kept its default Qualify the left side with this so it names the field A compiler warning about assignment to itself The same shadowing bug, caught before you ran

Challenge: Point Distance Squared