How can I force a Constructor to be defined in all subclass of my abstract class

You can’t force a particular signature of constructor in your subclass – but you can force it to go through a constructor in your abstract class taking two integers. Subclasses could call that constructor from a parameterless constructor, passing in constants, for example. That’s the closest you can come though.

Moreover, as you say, you don’t know anything about the implementation – so how do you know that it’s appropriate for them to have a constructor which requires two integers? What if one of them needs a String as well? Or possibly it makes sense for it to use a constant for one of those integers.

What’s the bigger picture here – why do you want to force a particular constructor signature on your subclasses? (As I say, you can’t actually do this, but if you explain why you want it, a solution might present itself.)

One option is to have a separate interface for a factory:

interface MyClassFactory
{
    MyClass newInstance(int x, int y);
}

Then each of your concrete subclasses of MyClass would also need a factory which knew how to build an instance given two integers. It’s not terribly convenient though – and you’d still need to build instances of the factories themselves. Again, what’s the real situation here?

Leave a Comment