Reputation: 87
public class MotoXCellPhone {
//assume there's a speaker class
private BlueToothSpeaker speaker;
//why instantiate in constructor?
MotoXCellPhone() {
speaker = new BlueToothSpeaker();
}
//or if i instantiate in a method?
public BlueToothSpeaker useSpeaker() {
speaker = new BlueToothSpeaker();
return speaker;
}
}
why would i want to instantiate a class in another class' constructor? i don't fully understand composition yet so i'm fuzzy on the 'why" of everything
Upvotes: 0
Views: 49
Reputation: 32833
There are two types of member initialization, each with pros and cons, I'll try to enumerate them:
early-initialization:
lazy-initialization:
Depending of the implementation of your class you might choose one over another.
Upvotes: 0
Reputation: 46
The constructor will run and instantiate BlueToothSpeaker right when MotoXCell is instantiated, whereas the method will only instantiate the new class when it is called.
Upvotes: 0
Reputation: 20185
The argument is as follows: if someone else uses your code, they might not call useSpeakser()
and thus speakers
might be null
. Instantiating speakers
within the constructor asserts that it will not be null
.
Upvotes: 1
Reputation: 198171
If you instantiate it in the method, you'll create a new one each time that method is called. If that doesn't make sense -- if you want one BlueToothSpeaker
object to be tied to the MotoXCellPhone
object for its lifetime -- then you need to create it (or inject it) in the constructor.
Upvotes: 1