I have no doubt this has been asked and answered here a dozen times, but I just can’t find a satisfactory answer.
I have a family of classes that I only want instantiated by the abstract parent class through a static method like this (I probably have typos here I am typing without trying to compile).
public abstract class Papa {
public static Papa newInstance() {
String strClass = Papa.figureOutTheNameOfChildClassToInstantiate();
Papa papa = (Papa) Class.forName(strClass).newInstance();
return papa;
}
public abstract void doSomething();
...
}
public class Child extends Papa {
public void doSomething() { /* Do something */ }
}
That’s more or less what I have now. What I wish to do is be sure that the Child can only be instantiated by the factory method Papa.newInstance(). I tried to do this by making the Child’s no-argument constructor private, but then Papa can’t instantiate it.
So, my question is, how can I make sure Child instances are only created by the factory method Papa.newInstance()?
If you absolutely, positively, want to enforce this, then give
Papaa protected constructor which takes a parameter of typeXyzzy. MakeXyzzya protected inner class inPapa. Give it a private constructor. Now, onlyPapacan make instances ofXyzzy. Since you need an instance ofXyzzyto callPapa‘s constructor, and since subclasses ofPapamust call its constructor from their constructors, you need an instance ofXyzzyto call the constructor of any subclass ofPapa. Hence, onlyPapacan call the constructors of its subclasses. Even thoughXyzzydoesn’t do anything.Subclasses could leak their
Xyzzyinstance, which would allow other code to call subclass constructors. But you can constrain that too, by makingXyzzysingle-use, and only so within the context of a single static factory invocation.But to be honest, i wouldn’t bother!