Reputation: 279
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?
Upvotes: 3
Views: 87
Reputation: 6557
Yes, as these 2 approaches give different behaviour, hence one may be preffered over the other:
In 2nd approach, class members are automatically initialized by the compiler using the default constructor, unless you call init method and set the values to your required initial values.
So, setting
will be 0 by default when the object is created. Now, if you do not call init() on the newly created object and use it in your program, this may lead to undesirable behaviour. This is the reason the constructor approach is preffered.
However, placing too much code in constructor may lead to poor responsiveness, and also produces undesired results in case of inheritence. For such reasons, First approach is not preffered in general.
Upvotes: 2
Reputation: 1584
As per the codes in your question: Whenver you use setting and want it to be initialized you need to use the argument constructor SomeClass(int setting) like:
SomeClass someClass=new SomeClass(12);
And in the second case you need to call the method by passing the argument to get it initialised as in:
SomeClass someClass=new SomeClass(6);
someClass.init(6);
This depends on your requirement ,however initializing a variable using a constructor is mostly preferred.
Upvotes: 2
Reputation: 1500305
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.
Upvotes: 5