Resume of Seth Long
Resume of Seth Long Download Resume
Home blog Resume Contact
Resume of Seth Long

Archive for May, 2008

Inheritance

Thursday, May 8th, 2008

A good friend of mine called me up the other day and said he was getting back into programming after being away from it for many years.  He was having a hard time understand the concept of inheritance and asked me for a really easy to understand example.  So here it is…

The easiest way to understand inheritance is to think about your parents.  Ok, I know you’re wondering what thinking about your parents has to do with programming but let me explain.  You are a unique individual yet you share many of the same features as your parents.  You inherited those features from you parents and combined them with your own features, creating a new and unique individual.  Well, inheritance in programming isn’t much different.  You create a new class that inherits the properties and methods of another class.

For this example, we will have a class named AlcoholicBeverage.  In case you didn’t know, all alcoholic beverages contain alcohol and have a “proof”.  So, we’ll add the properties “Proof” and “AlcoholPercent” to the AlcoholicBeverage class.  This class will act as the “parent” for our future beer and wine classes.

class AlcoholicBeverage
{
    protected double _PercentAlcohol;
    public double Proof
    {
        get { return (_PercentAlcohol * 2); }
        set { _PercentAlcohol = (value / 2); }
    }
    public double PercentAlcohol
    {
        get { return _PercentAlcohol; }
        set { _PercentAlcohol = value; }
    }
}

Next, we will create our beer and wine class which will inherit from the AlcoholicBeverage class.  A beer and a glass of wine both have a percentage of alcohol and a proof but we will not need to add them to our beer and wine classes since they are already defined in the base AlcoholicBeverage class.

class Beer : AlcoholicBeverage
{
    public Beer()
    {
        PercentAlcohol = 2.5;
    }
}
 
class Wine : AlcoholicBeverage
{
    public Wine()
    {
        PercentAlcohol = 12;
    }
}

Now we can create our new beer and wine classes and check their Proof.

Beer bottleOfBeer = new Beer();
Console.WriteLine(bottleOfBeer.Proof.ToString());
 
Wine glassOfWine = new Wine();
Console.WriteLine(glassOfWine.Proof.ToString());

When run, it gives the following output:

5
24

This is a really simple example of inheritance.  Hopefully it’s simple enough for everyone to understand.  Well, that’s all for now!

- Seth Long

home   |   blog   |   resume   |   contact

© 2009  Seth Long   An accomplished senior software engineer living in the San Francisco Bay Area.
Specializing in PHP, MySQL, Linux, Apache, LAMP, AJAX, JavaScript, C#, MS SQL Development.