Friday, January 20, 2012

Classes: Inheritance

One of the biggest aims of object-oriented programming is code reuse. Why write and debug your own code, when there's already code that does the same thing? Inheritance is a form of code reuse that is especially handy for specializing a class that already exists. When a superclass is inherited by a subclass all of its attributes and methods are passed down. You can then specialize by adding your own unique attributes and methods.

For instance, let's say you're writing a laptop class. There's already a computer class that includes a word processor, access to the internet, a terminal, a keyboard, and a mouse. Laptops use (or can use) all of these things, so you don't need to rewrite all of that code. Instead, you can use inheritance to implement all of this code, and add some of your own (smaller, a track pad instead of a mouse, etc). You could also write a desktop class that also inherits code from the computer class.

Python


class Laptop (Computer):
    """ A laptop computer"""
    def __init__ (self, monitor_size)
        self.size = monitor_size


C++


class Laptop: public Computer
{
    private:
        int size;

    public:
        Laptop (int monitor_size)
        {
            size = monitor_size;
        }
};


Java


public class Laptop extends Computer {

    private int size;

    public Laptop (int monitorSize) {
        size = monitorSize;
    }

}

  • In Python, creating a subclass is the same as creating a superclass, except the keyword "object" that is normally in the parenthesis is replaced by the name of the class you are inheriting from ("Computer" in this case).
  • In C++ a subclass is defined with the following structure:

    class SubClassName: accessSpecifier SuperClassName
    {
        code;
    };
    • The access specifier controls the class's visibility, and this can be public, private, or protected. Public allows the class to be accessed anywhere in the program, protected allows the class to be accessed by itself and its subclasses, and private restricts access to the class itself.
    • As usual, a semicolon is required at the end of the class declaration.
  • In Java a subclass is defined with the following structure:

    accessSpecifier class SubClassName extends SuperClassName {
        code;
    }
    • extends is a special keyword in Java that is used to specify a subclass's superclass.
    • an access specifier is included before every Java class to indicate what other classes may access it.
  • It is important to note that every method that is accessible in the computer class, should be accessible in the laptop class. So laptop.access_internet(browser) should work just as well as computer.access_internet(browser).

No comments:

Post a Comment