Next: , Up: Inheritance   [Contents]


2.2.3 Understanding Member Inheritance

In Figure 2.15, we took a look at how to inherit from a parent class. What does it mean when we “inherit” from a parent? What are we inheriting? The answer is: the API.

There are two types of APIs that subtypes can inherit from their parents:

Public API

This is the API that is accessible to everyone using your class. It contains all public members. We will be focusing on public members in this chapter.

Protected API

Protected members make up a protected API, which is an API available to subclasses but not the outside world. This is discussed more in the Access Modifiers section (see Access Modifiers), so we’re going to leave this untouched for now.

When a subtype inherits a member from its parent, it acts almost as if that member was defined in the class itself5. This means that the subtype can use the inherited members as if they were its own (keep in mind that members also include properties). This means that we do not have to redefine the members in order to use them ourselves.

LazyDog and TwoLeggedDog both inherit the walk() and bark() methods from the Dog supertype. Using LazyDog as an example, let’s see what happens when we attempt to use the bark() method inherited from the parent.

    var LazyDog = Class( 'LazyDog' ).extend( Dog,
    {
        /**
         * Bark when we're poked
         */
        'virtual public poke': function()
        {
            this.bark();
        }
    } );

    // poke() a new instance of LazyDog
    LazyDog().poke();

    // Output:
    // Woof!

Figure 2.16: Using inherited members

In Figure 2.16 above, we added a poke() method to our LazyDog class. This method will call the bark() method that was inherited from Dog. If we actually run the example, you will notice that the dog does indeed bark, showing that we are able to call our parent’s method even though we did not define it ourselves.


Footnotes

(5)

This statement is not to imply that inheritance is a case of copy-and-paste. There are slight variations, which are discussed in more detail in the Access Modifiers section (see Access Modifiers).


Next: , Up: Inheritance   [Contents]