Microsoft.NET

……………………………………………….Expertise in .NET Technologies

The second pillar of OOP’s – Inheritance in C# – Part 11

Posted by Ravi Varma Thumati on July 13, 2009

The second pillar of Object-Oriented Programming – Inheritance

In this part of the object-oriented programming series I will introduce the second pillar of object oriented programming (inheritance); you will see how to use inheritance to create classes based on existing classes.

Introduction:

Inheritance gives you the ability of building a new classes based on existing class. So that it allows you to extend a base class by enabling a new class to inherit its characteristics and behavior.

The greatest thing with inheritance is that it gives you the ability of code reuse, so if you have a class which has some functionality, characteristics and behavior and you want to create another class which will has the same functionality but with some new characteristics and behaviors so instead of create a brand new class that have the same code you done before, all you need to is to create the new class and add to it only the new characteristics and behavior and inherit the other from the old class.

The Base class:

The base class is a normal class that has characteristics (variables) and behaviors (methods) that are common for all subclasses.

Example:

public class Car

{

string model;

int currentSpeed;

int maxSpeed;

public Car()

{ }

public Car(string model, int currentSpeed, int maxSpeed)

{

this.model = model;

this.currentSpeed = currentSpeed;

this.maxSpeed = maxSpeed;

}

public string Model

{

get { return model; }

set { model = value; }

}

public int CurrentSpeed

{

get { return currentSpeed; }

set { currentSpeed = value; }

}

public int MaxSpeed

{

get { return maxSpeed; }

set { maxSpeed = value; }

}

}

As you can see the car class has characteristics that any car of each type can have so it have the general variables that are common for any car.

The Subclass (derived class):

The subclass is a class that inherit its core functionality from a base class then it add its own functionality

Example:

public class BMW : Car

{

}

We left our BMW class with out adding any variables or methods so the BMW class is the same as the Car class so if you tried to use it you will see that it have all characteristics of the Car class.

Example:

BMW bmw1 = new BMW();

bmw1.Model = “X5”;

bmw1.CurrentSpeed = 0;

bmw1.MaxSpeed = 230;

So let us see how we can extend our Car type by adding some functionality to its childe BMW.

Creating the subclass:

As I said all you need to do with your subclass is to add the new functionality to it and it will inherit all the common functionality from the base class.

Example:

public class BMW : Car

{

bool isFullOption;

bool hasDVD;

public BMW()

{ }

public BMW(string model, int currentSpeed, int maxSpeed, bool isFullOption, bool hasDVD)

{

//using the BMW class variables

this.isFullOption = isFullOption;

this.hasDVD = hasDVD;

//using the CAR class properties

Model = model;

CurrentSpeed = currentSpeed;

MaxSpeed = maxSpeed;

}

}

As you saw we create the BMW subclass and add two other variables to it (isFullOption, hasDVD) also we created a custom constructor and use it to assign the value of the BMW class variables and the properties inherited from the base class Car.

Using the base class constructors:

Instead of creating a custom constructor in the subclass that have the same code in the base class constructor, we can create a constructor that call the base class constructor and use the subclass constructor to assign values to the variables that belongs to the subclass.

Example:

public class BMW : Car

{

bool isFullOption;

bool hasDVD;

public BMW()

{ }

public BMW(bool isFullOption, bool hasDVD, string model, int currentSpeed, int maxSpeed)

: base(model, currentSpeed, maxSpeed)

{

//using the BMW class variables

this.isFullOption = isFullOption;

this.hasDVD = hasDVD;

}

}

We here create a custom constructor in the subclass and we will use it to receive values from the object user like (isFullOption, hasDVD, model, currentSpeed, and maxSpeed) and then we assigned the (isFullOption, hasDVD) values in the subclass constructor and pass the (model, currentSpeed, and maxSpeed) values to the base class constructor.

BMW bmw1 = new BMW(true, true, “X5”, 100, 230);

the first two parameters will be used by the subclass constructor and the last three will be use by the base class constructor.

Allowing the subclass to see the base class variables (the protected keyword):

as you saw previously all the base class members are private so the subclass can not see it and can only deal with it by its properties, so if we want the subclasses to see the variables of the base class we have to redefine these variables as protected.

public class Car

{

protected string model;

protected int currentSpeed;

protected int maxSpeed;

public Car()

{ }

public Car(string model, int currentSpeed, int maxSpeed)

{

this.model = model;

this.currentSpeed = currentSpeed;

this.maxSpeed = maxSpeed;

}

}

The protected keyword means that the base class variables are accessible only by the subclasses and private to all other classes.

By using protected members we created a level of trust between the base and derived classes.

We now can use the Car class variables directly in the BMW subclass with out using any properties.

public class BMW : Car

{

bool isFullOption;

bool hasDVD;

public BMW()

{

//we now can use the member of the base class

currentSpeed = 0;

maxSpeed = 230;

}

public BMW(bool isFullOption, bool hasDVD, string model, int currentSpeed, int maxSpeed)

: base(model, currentSpeed, maxSpeed)

{

//using the BMW class variables

this.isFullOption = isFullOption;

this.hasDVD = hasDVD;

}

}

The sealed classes:

We can create classes that can not be inherited by using sealed keyword in the class definition, so if we tried to inherit from a sealed class we will have a compile time error.

Example:

We can define our BMW class as sealed class

public sealed class BMW : Car

{

bool isFullOption;

bool hasDVD;

public BMW()

{

//we now can use the member of the base class

currentSpeed = 0;

maxSpeed = 230;

}

public BMW(bool isFullOption, bool hasDVD, string model, int currentSpeed, int maxSpeed)

: base(model, currentSpeed, maxSpeed)

{

//using the BMW class variables

this.isFullOption = isFullOption;

this.hasDVD = hasDVD;

}

}

If we tried to inherit from BMW class we will have a compile time error.

//Compile time error

public class MiniCoper : BMW

{

}

Note: C# dose not allow multiple base classes, so any class can inherit only from one base class.

Multiple Inheritances in C#

Can you inherit from multiple classes in C#? Simply put, this cannot be done. However there are ways around it. From a design perspective you must ask yourself, will a Class fully represent an object?

Can you inherit from multiple classes in C#? Simply put, this cannot be done. However there are ways around it. From a design perspective you must ask yourself, Will a Class fully represent an object? Meaning that, if we have a base class with abstract methods designed for a particular application and we know that the inheriting object will only need the methods defined in that class. We now have a valid design pattern here.

The Vehicle Car Object

Lets say we have an abstract class called “Vehicle” as well as another class called “ConstructionVehicle”. The vehicle class has methods such as Accelerate() , Stop(), and the “ConstructionVehicle” class has methods such as ExecuteDump() and TurnOnBackUpSound(). If we were only going to build a Car object and know we would only use those methods from the “Automobile” class this would be fine.

The DumpTruck Object

Now we want to create another object called “DumpTruck”. We could inherit from the Automobile class but that class does not have the methods that we need called ExecuteDump() and TurnOnBackUpSound(). If we were using a language such as C++ we could easily inherit from both classes using multiple inheritances. However, seeing C# is our language of choice, multiple inheritances is not an option; you may only inherit from one Base Class.

From Abstract Classes to Interfaces

From a design perspective we must choose a different design. C# supports what is called “Multiple Implementation”, which is to say a class can implement more than one interface. Our design now changes the “Vehicle” class and the “ConstructionVehicle” class into interfaces. Below we have defined the two interfaces with their very simplistic methods. i.e :

interface IConstructionVehicle
{
void ExecuteDump();
void TurnOnBackUpSound();
}
interface IVehicle
{
void Accelerate();
void Stop();
void TurnOnBackUpSound();
}

If we built a class that inherited from these two interfaces we would be able to do so spanning multiple inherited interfaces. Design problem solved!

Or is it?

Explicit Interface Implementation

If you look at both interfaces defined above you’ll notice that they share in common a method of the same name “TurnOnBackUpSound()”. Problem? No, in fact C# supports what is known as “Explicit Interface Implementation”, which allows the programmer to specify which member of which interface they want to use. Putting the Interface name in front of the member name allows this to happen as shown below.

public class DumpTruck: IEngine, IBody
{
void IEngine.Test()
{
Console.WriteLine(“This is the Engine TEst”);
}
void IBody.Test()
{
Console.WriteLine(“This is the Body TEst”);
}
}

Implementation Hiding

Another benefit to this technique is something called “Implementation Hiding”. Implementation Hiding allows the methods from the implemented interface to be hidden from the derived class unless the developer explicitly calls the interface. This technique obviously reduces the clutter for a developer.

Advertisements

2 Responses to “The second pillar of OOP’s – Inheritance in C# – Part 11”

  1. Thanks for the good writeup. It in fact was once a entertainment account it. Glance advanced to far delivered agreeable from you! By the way, how could we keep up a correspondence?

  2. Thanks for taking the time to debate this, I really feel strongly about it and love learning more on this topic. If doable, as you acquire expertise, would you thoughts updating your weblog with extra information? It is extremely useful for me.

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

 
%d bloggers like this: