I have an abstract class and several concrete classes which extend it.
The abstract class has two constructors. I want one of the constructors to only be callable in one particular concrete class.
(I do know about the enum
pattern for Java state machines, but two levels of subclassing (and immutable POJOs) work better for the problem I'm solving.)
public abstract class SuperState {
public final long mValue;
protected SuperState(long value) { mValue = value; }
protected SuperState(SuperState last) { mValue = last.mValue + 1; }
...
}
public class FirstState extends SuperState {
public FirstState() { super(0); }
...
}
public class SecondState extends SuperState {
public SecondState(SuperState last) { super(last); }
...
}
public class ThirdState extends SuperState {
public ThirdState(SuperState last) { super(last); }
...
}
I want to make it a compile-time (or at least runtime) error for any subclass (apart from FirstState
) to call the SuperState(long value)
constructor.
Could I find out the type of the concrete class being constructed in the SuperState
constructor, and throw a runtime exception if it's not as expected?
Is there a was of having a "preferred" concrete class for an abstract class, such that it has some form of extra access?