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).

Wednesday, January 11, 2012

Classes

A class is code containing attributes and methods that is used as a blueprint for creating objects. Objects are instances of the class, and therefore have a similar structure to the class. Classes can be created for any sort of object that you could possibly imagine.
For instance, a car class would have make, model, and color attributes, and it would have accelerate, turn, and brake methods.
A butterfly class would have species, color, and size attributes, and it would have fly and eat methods.
A light switch class would have a state attribute, and it would have turn on, turn off, and check state methods.

Classes
General Structure


class ClassName
    code


Python


class LightSwitch (object):
    """A virtual light switch"""
    def __init__ (self, state):
        self.state = state

    def turn_on ():
        self.state = on

    def turn_off ():
        self.state = off

    def check_state ():
        return self.state


C++


class LightSwitch
{
    private:
        bool state;

    public:
        LightSwitch (bool _state)
        void turn_on ();
        void turn_off ();
        bool check_state();
};

LightSwitch::LightSwitch (bool _state)

{
    state = _state;
}

void LightSwitch::turn_on ()
{
    state = on;
}

void LightSwitch::turn_off ()
{
    state = off;
}

bool LightSwitch::check_state ()
{
    return state;
}



Java


public class LightSwitch {

    private boolean state;

    public LightSwitch (boolean _state) {
        state = _state;
    }

    public void turnOn () {
        state = on;
    }

    public void turnOff () {
        state = off;
    }

    public boolean checkState () {
        return state;
    }

}


Constructors


A constructor is a special method used in classes to instantiate an object when it is first created. By convention, this is the first method that is defined in a class. In Python, the constructor class is called "__init__" and the first parameter is always "self" by convention. In C++ and Java, the constructor class is called whatever the class name is (so in this case the constructor is called "LightSwitch").

A constructor does not need any parameters to instantiate an object. This is a special case called a default constructor. If you include a default constructor then you define the class attributes, in addition to declaring them.

However, in most cases you will declare class attributes, and define them in the constructor through the constructor's parameters (such as, "state = _state").


  • In Python a class is defined with the following structure:

    class ClassName (baseClassName):
        code
    • As usual, the colon is essential to the definition.
    • The base class name is "object" unless you are using inheritance (to be explained in the next blog) 
    • Since variables do not have to be declared in Python, the keyword "self" is used to differentiate class variables from parameter variables. 
    • All class methods are defined within the class definition (using tabs to structure the definitions)
  • In C++ a class is declared with the following structure:

    class ClassName
    {
        code;
    };
    • It is important to include the semicolon at the end of any class declaration in C++.
    • Classes in C++ are private by default. This means that nothing in them is accessible from outside of the class without the public keyword.
    • In this particular example I defined the class's methods outside of the class declaration. If this is done then each method name needs to be preceded by the class name and two colons. 
      • The two colons together are defined as the scope operator, and it is essential to specifying which class the method belongs to.
  • In Java a class is defined with the following structure:

    class ClassName {
        code;
    }
    • Unlike C++, Java does not require a semicolon after class declarations.
    • Java is completely object oriented, so it is not possible to define a class's methods outside of the class declaration.
    • Other than those differences, class declarations are basically the same in C++ and Java.