Search code examples
objectoopinheritanceabap

How to enforce constructor signature across sub-classes?


I want to dynamically instantiate sub-classes of a given class, and I need a consistent signature for the sub-classes' constructors to avoid errors at runtime.

Constructors can be defined with arbitrary sets of parameters in each sub-class since constructors are not redefinitions. This can cause problems during dynamic instantiation if a sub-class defines a constructor with a different signature.

I need a dynamic sub-class instantiation because the logic itself to select the appropriate sub-class is dynamic. However, that logic is external in a relation to the instantiated classes.

Instead of defining a public constructor, I thought of defining a public static method create that would enforce the signature and return an instance of itself. However, static methods cannot be redefined in sub-classes.

Is there a way to enforce a consistent dynamic instantiation of sub-classes ?


Solution

  • I can't think of a way to prevent people inheriting from a class from creating an own constructor with different parameters.

    But what you can do is to not give the constructor any parameters, and have a separate method "initialize" instead. That method would then always get called by your framework after creating the object. That method can then be part of an interface those classes need to implement or an ABSTRACT method of the base-class they need to redefine. Which means they are forced to implement it with the correct parameters.

    It still doesn't prevent people from creating an own constructor with obligatory parameters. This would still prevent their class from working in the context of your framework. But the presence of a method "initialize" they must implement is a pretty broad hint that this is where their initialization should actually take place and that these are the parameters that contain the information that is available to them at initialization.