Suppose I have some Java code such as the following (in this case, the use of the name "interaction" is referring to interacting with an object in a video game):
public abstract class Interaction
{
private Interaction()
{
// ...
}
// base class stuff here, some public some private
public static final class OneShotInteraction extends Interaction
{
public OneShotInteraction()
{
// empty
}
}
public static final class OngoingInteraction extends Interaction
{
public OngoingInteraction()
{
// ...
}
// ...
}
public static final class ItemExchangeInteraction extends Interaction
{
public ItemExchangeInteraction()
{
// ...
}
// ...
}
public static final class InventoryInteraction extends Interaction
{
public InventoryInteraction()
{
// ...
}
// ...
}
}
In this code, I'm defining derived classes for handling different types of interactions that all inherit from a shared base class.
My reasons for structuring the code in this way are:
I want to limit the possible types of interactions to the ones defined here. I don't want code from other packages or modules being able to deliberately or inadvertently make their own interaction subclasses.
The interaction classes need to be able to access other package-protected members of the package that they're currently in.
I don't want to pollute the namespace of the package.
So I can't:
Put the derived classes in a separate package, because this requires using a public constructor in the base class and breaks (1).
Put the derived classes plus base class in a separate package, because this breaks (2).
Put the derived classes outside of the base class in the same package, because this breaks (3).
So my question is, would it be considered a bad pattern to put derived classes inside of their base class in this manner, considering the benefits that I see to namespace organisation and eliminating possible mistakes in the future?