Using Java's access modifiers you have two approach:
Encapsulate all child classes inside the parent class as private static
nested classes:
public abstract class GameObject {
private GameObject() {
}
private static class GameObjectImpl1 extends GameObject {
}
}
As constructor of the parent class is private it's not possible to extend it outside. Also it's not possible to instantiate GameObject
, as it is abstract.
The only downside of this approach is that you need to put all child classes literally inside the parent, i.e. the file gonna be large.
You can create separate dedicated package for your base class and all it's children. Make the base class (GameObject
) the only public class in this package. Make it's constructor package-private (child classes in the same package will still have access to it).
package game;
public abstract class GameObject {
GameObject() { //package-private
}
public static GameObject create() {
return new GameObjectImpl1();
}
}
//---------------
package game;
class GameObjectImpl1 extends GameObject { //package-private
}
The minor downside of this approach is that it can be "hacked" by creating package with the same name in other source root. Classes there will have access to your package-private classes inside the game
package. However, otherwise this is the most clean approach and I'd recommend taking it.