Coding Notes

Ideas and thoughts from Seth Long


My blog is now located at

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();
Wine glassOfWine = new Wine();


When run, it gives the following output:


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

May 8, 2008 Posted by | Architecture and Design Patterns | Leave a comment