From what I have seen in other peoples code, there appears to be two ways common ways in creating an object and "readying" it to be used.
Method 1: Ready the object in the constructor:
public class SomeClass {
int setting;
public SomeClass(int setting) {
this.setting = setting;
}
}
Method 2: Create the Object then "ready" it inside an initialize method such as:
public class SomeClass {
int setting;
public SomeClass(int setting) {
}
public void init(int setting) {
this.setting = setting;
}
}
Is there any specific reason to use either method over another?
One reason for using the constructor is that you can make the field final
- immutability isn't an option if you the constructed object isn't fully initialized. Personally I prefer to write code so that by the time an object is available, it's really ready to use - rather than having life-cycles of "construct, initialize, use".
On the other hand, doing a lot of work in a constructor is also generally frowned upon - partly because during construction you're potentially in an odd state as any subclasses won't have run their constructor bodies yet, so calling overridden methods in constructors is a bad idea.
Another alternative is to have a static
method which does most of the actual work, and then delegates to a constructor just passing in field values. Factory methods like this have additional benefits such as the ability to return null
where appropriate (rare, but it happens) or reuse existing objects.
See more on this question at Stackoverflow