Skipping an Abstract Generation

One of the issues of working with an existing OOP codebase is that the original author may have programmed abstract classes with a fixed class depth in mind. For example:

abstract class animal
{
    abstract function speak();
}

class dog extends animal
{
    function speak() {
        print "woof";
    }
}

class cat extends animal
{
    function speak() {
        print "meow";
    }
}

All is well in this quadroped example, but what if you decide you’d like to break cats down into seperate sub-species, but leave dogs as is? Presuming that you already have hundreds of animal extension classes written, it would be tedious to reconfigure the abstract base class to handle this exception. Luckily, abstract requirements can skip a generation:

abstract class animal
{
    abstract function speak();
}

class dog extends animal
{
    function speak() {
        print "woof";
    }
}

abstract class cat extends animal
{
    // some general cat methods
}

class kitten extends cat
{
    function speak() {
        print "meow";
    }
}

class lion extends cat
{
    function speak() {
        print "roar";
    }
}

The intermediate class needs to be declared as abstract to indicate that any requirements of both itself and its parent(s) are to be passed to its child. Because the child classes, such as kitten and lion, contain the speak() method, they have satisfied the abstract requirements of the grandparent class, animal. Meanwhile, the dog class still functions as before.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.