Basing a Class on Another Class—Subclassing

So far we have discussed just about all there is to know about objects. We have discussed what objects, properties, methods and events are. We have also discussed how we create an object's blueprint with a class which we then use to instantiate the object. One more important piece remains—the real exciting part as it turns out. Creating classes based on prior classes.

In our LIGHT class, we created an object that basically had one property and one method. This works real well for all the light switches in the world that just turn the light on and off. Suppose I want to create a light switch that dims as well? What do I do? Do I have to write a whole new class? The toggle is still applicable; you can still turn the light on and off. All I need is a modified version of the LIGHT class that has all the capabilities of the LIGHT class and one additional capability: dimming the light.

For the purposes of this illustration, I'll set the following rules. When you attempt to use the dimmer, it will go from full light to half light and then back again. In order to turn the light off or on, you still need to use the original lightswitch method.

Here's how we could accomplish this using an OOP model.


DEFINE CLASS dimmer AS light
  intensity = "FULL"

  PROCEDURE DimmIt
   IF this.status = "OFF"
     RETURN
   ENDIF
   
   this.intensity = IIF(this.intensity = "FULL", ;
              "HALF", "FULL")
   WAIT WINDOW "Lights are now "+this.intensity+" power."
  ENDPROC
ENDDEFINE

Note the original DEFINE of the class. In the original define (class LIGHT), we used CUSTOM as the base class. CUSTOM basically means that there is no base class, we are creating one from scratch. In the DEFINE we use here, the base class is LIGHT. This means that DIMMER automatically gets everything that LIGHT has. Thus, although no code exists in the DIMMER class to handle the LIGHTSWITCH method and the status property, DIMMER gets it automatically by virtue of it being a subclass of LIGHT.

In effect, a subclass (e.g., DIMMER) is a more specialized version of the "super class" (e.g., LIGHT).

This is known as Inheritance.