aspose file tools*
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
Author

constructor

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
Bartender

Joined: Sep 13, 2007
Posts: 2366
    
    7

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/OCM-JD OCPJP7 OCPWCD5
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38351
    
  23
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.


SCJA
~Currently preparing for SCJP6
Saifuddin Merchant
Ranch Hand

Joined: Feb 08, 2009
Posts: 605

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: http://aspose.com/file-tools
 
subject: constructor