Reputation: 169
This problem easier to understand with code than with words:
Map<Integer, Parent> objectMap = new HashMap<Integer, Parent>();
Parent myParent;
Child1 myChild1;
Child2 myChild2;
//A lot more myChilds
objectMap.put(1, myChild1);
objectMap.put(2, myChild2);
//Place all the myChilds
myChild1 = new Child1(); //Constructor is expensive, object may not get used
myChild2 = new Child2(); //Constructor is expensive, object may not get used
//Call constructor for all of myChilds
Parent finalObject;
int number = 1; //This can be any number
finalObject = objectMap.get(number);
As you see, I don't know in advance which class will finalObject be. The code works without problem, but here is my question:
How can I avoid calling both constructors?
As only myChild1 or myChild2 will be used and the constructor methods are quite expensive, I want to only call the one that will actually get used.
Something like
finalObject.callConstructor();
in the last line
Any ideas?
Thanks in advance.
EDIT: What I want to know is how to call the constructor without knowing the name of the class. Check the updated code.
Upvotes: 0
Views: 91
Reputation: 127
First check your condition and then inside the if or else statement call the constructor. if(condition) finalobject = new myChild1(); else finalobject = new myChild2();
Upvotes: 0
Reputation: 372784
How about this?
Parent finalObject;
if (condition) {
finalObject = new Child1();
} else {
finalObject = new Child2();
}
Or, even better, this?
Parent finalObject = condition? new Child1() : new Child2();
Upvotes: 4
Reputation: 11022
You should use the factory pattern :
public interface Factory<T> {
T create();
}
...
Factory<T> factory;
if (condition) {
factory = FACTORY1;
} else {
factory = FACTORY2;
}
object = factory.create()
Upvotes: 0
Reputation: 11832
Don't construct both objects. Only construct the object you need.
Parent finalObject;
if (condition) {
finalObject = new Child1();
} else {
finalObject = new Child2();
}
Upvotes: 1