File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "constructor" Watch "constructor" New topic


nimo frey
Ranch Hand

Joined: Jun 28, 2008
Posts: 580
In a constructor, what should I prefer:

or this

Where is the difference?
K. Tsang

Joined: Sep 13, 2007
Posts: 3132

If setProp is a method in that class then there really is no difference. For version 1 the "this" is not needed. The version 2 is useful if the class is NOT a JavaBean (meaning does have get/set methods ONLY).

K. Tsang JavaRanch SCJP5 SCJD OCPJP7 OCPWCD5 OCPBCD5 OCPWSD5 OCMJEA5 part 1 part 2/3
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46397
If you use the first format, the method called should have private access or a final modifier. So I would prefer the second.

Beware: if you use a class called "Const" there is a risk of using the keyword "const" by mistake.
Brian Legg
Ranch Hand

Joined: Nov 07, 2008
Posts: 488
I would prefer the first option. You have no idea what prop is equal to when it is passed to your constructor but you immediately set this.prop equal to it. Maybe this isn't an issue, but lets say that you are expecting prop to be between 0 and 500 or some other constraint. By passing the value to setProp() method you can check the value to make sure it is valid before setting this.prop equal to it. Yes, you could do the same thing in your constructor but if setProp() is a public method then you will have duplicate code which is always frowned upon. Assuming you don't care what prop is and/or your setProp() method is either not public or contains no logic then either choice is fine.... otherwise option 1 is the best IMHO.

~Currently preparing for SCJP6
Saifuddin Merchant
Ranch Hand

Joined: Feb 08, 2009
Posts: 607

Seems more a matter of style generally - Brian brought up a suitable point and in the case he mentions his logic makes perfect sense!

I'd prefer the second just because I more used to it ...

Cheers - Sam.
Twisters - The new age Java Quiz || My Blog
I agree. Here's the link:
subject: constructor
It's not a secret anymore!