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: Key points: - this always refers to the object the method is running on . - Use this.field = param; to assign a parameter to a same-named instance variable. - this is only meaningful inside instance methods and constructors, never inside static methods.

Challenge: Point Distance Squared