There are many answers to this question here on SO, but I wish to add a small bit of twist in my question. Consider a parent class Parent and it's children Child1 and Child2. Now, let their structure be something like below:
public abstract class Parent {
public abstract String eat();
public abstract String sleep();
public static Parent createInstance (int childType) {
if (childType == 1)
return new Child1();
else
return new Child2();
}
}
public class Child1 extends Parent {
public String eat() {
return "nom-nom";
}
public String sleep() {
return "zzzz...";
}
}
public class Child2 extends Parent {
public String eat() {
return "gulp-gulp";
}
public String sleep() {
return "ZzZz...";
}
}
Now, my questions are:
- Am I doing something wrong from pure OOP standpoint, by calling the child classes from the parent class?
- Can the above approach be called as an example for strategy design pattern, if I use it in the following way?
// In some random class:
public String showMeHowYouEat (int childType) {
Parent foo = Parent.createInstance(childType);
return foo.eat();
}
public String showMeHowYouSleep (int childType) {
Parent foo = Parent.createInstance(childType);
return foo.sleep();
}
Note : I've selected the above approach of creating child class instances from parent class is because I do not wish to write if-else every time I have to invoke the eat or sleep methods based on the childType.
My main intention behind asking this question was to simply understand if I'm breaking some rules of OOP paradigm by creating an instance of child from the parent class based on some input. And if I'm doing so, then what could be a better alternative to the above mentioned approach?
Parent.createInstancein the first place? Why wouldParent foo = Parent.createInstance(1);be better thanParent foo = new Child1();?childType