Design – Using abstract methods to force subclasses to define values for member fields

abstract classdesign

Often in my designs I define an abstract superclass whose subclasses will vary mostly in their values for the fields defined in the superclass.

For example, in a game I'm developing there's an abstract class Missile with a number of subclasses. Each one defines a different value for member variables such as MAX_SPEED, MASS, FLYING_FORCE, which are then used in calculations performed in the superclass.

I use abstract methods in Missile to force it's subclasses to define these variables. For example I simply have an abstract method defineMass() that forces subclasses to define their own value of mass.

A different example would be my Entity class (the superclass of all game-play classes) defining an abstract loadImage() method that forces subclasses to define an image for themselves.

Is this good practice? Is it common?

Best Answer

I think inheritance deserves better purposes:

  • If the only thing varying between subclases, and between subclasses and its superclass are the values of some members, then you are abusing inheritance or using it wrong. You could use builder pattern to create missiles with different values. If builder pattern is too complex for the task, factory methods like buildMissileOfTypeA() and buildSuperMassiveMissile() would do.
  • You would be putting inheritance to good use if the abstract methods were related to behaviors that the subclasses would implement in potentially different ways, but not just to set a value of a member.
  • Besides, you are not really forcing subclasses to define their own value, they just can simply implement an empty method that doesn't change the value of the mass and the compiler will be happy with it.