Inheritance
My blog is now located at http://www.WhoIsSethLong.com
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
No comments yet.
Leave a Reply
-
Archives
- May 2008 (1)
- February 2008 (3)
- January 2008 (6)
-
Categories
-
RSS
Entries RSS
Comments RSS
Hello, my name is Seth Long and I’m a Senior Software Engineer for SpeedDate.com in the San Francisco Bay Area.