Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Beginning Java and the fly likes this-operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "this-operator" Watch "this-operator" New topic
Author

this-operator

nimo frey
Ranch Hand

Joined: Jun 28, 2008
Posts: 580
What is best-practice:

Should I write the "this"-Operator explicitly or can I delete it?

What is better?



or



I know, it makes no difference but I have a lot of this.-in my java-files and want to delete the "this".

Should I do that?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

It's up to you, it depends on what style you personally prefer. If you add the "this", it makes it explicitly clear that you're calling a method on the current object. Personally, I prefer to not use the "this" too much in Java.

Note: "this" is not an operator, it's simply a reference to the current object.
[ October 24, 2008: Message edited by: Jesper Young ]

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Bill Shirley
Ranch Hand

Joined: Nov 08, 2007
Posts: 457
FYI ADMINS:

I was redirected here from

http://www.coderanch.com/forums/

a topic moved from Advanced to Beginner (but linking to the wrong one)


Bill Shirley - bshirley - frazerbilt.com
if (Posts < 30) you.read( JavaRanchFAQ);
Pawan Arora
Ranch Hand

Joined: Sep 14, 2008
Posts: 105
Consider an example

if you don't use this.i here with instance variable then constructor will explicitly assign the value of local variable i to itself.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37958
    
  22
Agree; that is a situation where the this keyword is necessary. [pedantic mode]But it's not a local variable you are reasigning; it's the parameter being reassigned to itself.[/pedantic mode]
 
jQuery in Action, 2nd edition
 
subject: this-operator
 
Similar Threads
retreiving all rows from a mysql table to a jsp page
Alternative to if else block
Deleteing the directory.
Hibernate delete
final static char sc = 'A';