Object Oriented Programming Part 3: Inheritance, Encapsulation, and Polymorphism Are Awesome

I’m taking a different approach to these blog posts and am trying to be more natural. I usually don’t talk stuffy in real life, and this is a blog, so I am going to be all natural with the way I write.

Here goes nothing.

Inheritance, Encapsulation, and Polymorphism are the three pillars of OOP and allows us to do some pretty cool things. Don’t believe me? I’ll show you after the break.

These are the concepts in a nutshell:

Encapsulation is when you hide functionality from other classes so they can’t muck with it. How would you accomplish that? Hint: we talked about it in part 2.

Inheritance is when a class derives from another. Inheritance is a “is a” relationship.

Polymorphism is when we can make an object behave like another.

Alright, let’s see this in action.

But first, everything is awesome.

Okay, now that we have established everything is awesome, let’s just see exactly how awesome it is, shall we?

Inheritance

Let’s create a class named “LEGO.cs” in a new console application:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EverythingIsAwesome
{
    class LEGO : Awesome
    {
        public string LegoIsAwesome()
        {
            return "LEGO is awesome.";
        }      
    }
}

The “: Awesome” means that the class LEGO inherits from a class named Awesome. Let’s go ahead and create that class now:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EverythingIsAwesome
{
    class Awesome
    {
        public string IAmAwesome()
        {
            return "I am awesome.";
        }
    }
}

“class LEGO : Awesome” can be read as “LEGO is Awesome”. It is isn’t it?

Now, back in the Main method in Program.cs, let’s write some code to see inheritance in action.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EverythingIsAwesome
{
    class Program   //  Not Awesome
    {
        static void Main(string[] args)
        {           
            var newLego = new LEGO();
            Console.WriteLine(newLego.LegoIsAwesome()); //This is in the Lego class.
            Console.WriteLine(newLego.IAmAwesome());      // This is in the Awesome class.     
            Console.ReadLine();
       }        
    }
}

Notice how we were able to access methods in both the LEGO and Awesome classes? This was made possible through the awesome use of inheritance. A Lego is (a) Awesome, therefore we can access anything that is exposed in Awesome via a Lego object.

Encapsulation

Encapsulation is pretty easy to wrap your head around: it just means that you are hiding variables, methods, properties, etc. from other classes.

Polymorphism

To continue on this very awesome sample application, let’s go ahead and add a new type of component called an interface.

An interface is simply a file that contains no implementation, just stubs. When a class implements an interface, it must provide full implementation for each method, property, etc. that is declared in the interface.

Create a new interface item by right-clicking on your project in Solution Explorer, selecting “Add New Item” option (or just press Ctrl + Shift + A), then select “Interface” from the options.

image

Name the interface IBrick.cs.

This interface will allow us to specify what every brick should have. So, a brick has a color, a height, width, and it is awesome. Make your interface file look like this:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EverythingIsAwesome
{
    interface IBrick
    {
        Color BrickColor { get; set; }
        int BrickHeight { get; set; }
        int BrickWidth { get; set; }
        string BricksAreAwesome();
    }
}

Now, create a new brick class. Name it “RedBrick.cs”. It inherits from LEGO and implements the IBrick interface.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EverythingIsAwesome
{
    class RedBrick : LEGO, IBrick
    {
        public RedBrick()
        {
            BrickColor = Color.Red;
            BrickHeight = 20;
            BrickWidth = 20;
        }

        private Color _brickColor;
        public System.Drawing.Color BrickColor
        {
            get
            {
                return _brickColor;
            }
            set
            {
                _brickColor = value;
            }
        }

        private int _brickHeight;
        public int BrickHeight
        {
            get
            {
                return _brickHeight;
            }
            set
            {
                _brickHeight = value;
            }
        }

        private int _brickWidth;
        public int BrickWidth
        {
            get
            {
                return _brickWidth;
            }
            set
            {
                _brickWidth = value;
            }
        }

        public string BricksAreAwesome()
        {
            return "Red Bricks are awesome!";
        }

        public string EveryRedBrickIsAwesome()
        {
            return "Everything is awesome if you are a red brick!";
        }
    }
}

The default constructor sets up some default values for us.

Notice the private member variables. These are encapsulated and can only be used within the class itself. The properties are exposed to other classes and are used to set these private variables. These properties, as well as the method “BricksAreAwesome” are implementations from the interface.

The interface can be considered as a contract between a class and itself. A class that implements an interface must implement its methods and properties.

Go ahead and create another colored brick class that inherits from LEGO and implements IBrick. I won’t provide code for this since an example is provided above!

I’ll wait.

Okay, now that you have done that, let’s see some Polymorphism in action. Go into your Program.cs class and add the following code in the Main method:

List<IBrick> bricks = new List<IBrick>(); // This is a list of IBricks.Any class that implements an IBrick can be added to this list.
bricks.Add(new RedBrick());
bricks.Add(new BlackBrick()); // Or whatever you called your second colored brick class!

foreach(IBrick item in bricks)
{
     Console.WriteLine(item.BricksAreAwesome());

     if(item is RedBrick)
    {
               var redBrick = ((RedBrick)item);
               Console.WriteLine(redBrick.EveryRedBrickIsAwesome());
               Console.WriteLine(redBrick.LegoIsAwesome());
               Console.WriteLine(redBrick.IAmAwesome());
               Console.WriteLine("...................................");
     }
     if(item is BlackBrick) // Or whatever you called your second colored brick class.
    {
                var blackBrick = ((BlackBrick)item);
                Console.WriteLine(blackBrick.EveryBlackBrickIsAwesome());
                Console.WriteLine(blackBrick.LegoIsAwesome());
                Console.WriteLine(blackBrick.IAmAwesome());
                Console.WriteLine("........................................");
    }
}

We could also check the color, height, and width if we wanted to. How would you do that?

That’s it for now. Next week we will talk about ASP.NET WebForms. The remainder of this series will focus solely on that, complete with a project!

Thoughts

What do you, dear reader, think of this series so far? Let the world know in the comments! (NOTE: the comments are moderated, so try not to be too brutal.)

I put a “completed” version of this project on github: https://github.com/muffinman29/AwesomeOOP.

LEGO®is a trademark of the LEGO Group of companies which does not sponsor, authorize or endorse this site.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s