Inheritance in C Sharp

Inheritance in C Sharp

Inheritance describes the software engineering concept that allows one class to use the properties and methods of another class. OOP, or Object Oriented Programming, includes mechanisms for implementing inheritance. The C Sharp (C#) programming language supports the creation of base classes and derived classes. In this tutorial we introduce inheritance through examples and code along with discussion of those examples. At the end of the presentation we provide a complete working program illustrating our concepts.

The purpose of inheritance is to facilitate reusable software components and also to allow programmers and designers to model entities in the real world. Conceptually, humans view their world as a collection of interacting objects. These objects have behavior (methods) and data (properties). Methods are usually implemented as verbs and properties as nouns or adjectives. For example, a car object might have properties such as color, model, and license plate number. A car might have behaviors such as turn, stop, or crash. Designing an object requires some business knowledge. In other words, in order to accurately specify the properties and methods of an object, the designer must understand how the object interacts with other objects in the real world.

Objects are grouped into classes. A class is a template defining the properties and methods for all the objects that will be created from that class. In programming parlance, a class is a data type and an object is an instance of that data type, also referred to as a variable.

Continuing with our car analogy, we observe that some properties and methods might be common to all car classes. Obviously a car class that models a car on a used car sales lot will differ from a car class modeling a vehicle speeding around a race track. As different as these models may be, they still share some common characteristics. These common characteristics could be grouped together into a base class that would then be shared by the used car class and the race car class.

Every Class is Artitrary

Designing a class is an exercise in the application of business knowledge and software engineering. A class should provide a useful model but not a universal model. The classes presented in this tutorial are intended to illustrate software development concepts. They are not intended to be useful models of real-world entities. Every class could be tweaked and polished ad infinitum: the reader should try to resist that temptation.

Introduce our Base Class

We introduce our base class, which will contain properties and methods common to all our derived classes. The class, called Car, contains two properties called intTopSpeed and strModel; Certainly this class is imcomplete. It is not intended to accurately model any car objects in the real world.

The code for our base class follows:

/// <summary>
/// Our base class
/// </summary>
class Car
{
	private int intTopSpeed;
	private String strModel;
}

We arbitrarily elected to define the model property as a string and the topSpeed property as an integer. Note that even this simple base class requires some domain knowledge.

Access specifiers are beyond the scope of this tutorial, but in the interest of good programming and effective design we have declared our properties as private. In other words, these variable are only accessible to members of the class. They are only visible within the base class.

In order to make these properties available to our derived classes, we provide a 'get' and a 'set' method for each. The structure of the get and set are specific to the C# (C Sharp) programming language but should be understandable with a modicum of study. The get and set code is declared as public, implying that it will be visible to our derived classes.

Adding our gets and sets results in the following code:

// Car.cs
// (c) nicomp
/// <summary>
/// Our base class
/// </summary>
class Car
{
     private int intTopSpeed;
     private String strModel;
     public int topSpeed
     {
         get
         {
             return intTopSpeed;
         }
         set
         {
             intTopSpeed = value;
         }
      }
}

Here come the derived classes

Our base class may have some limited application by itself, but the purpose of this tutorial is to illustrate the base class / derived class relationship. To that end, we introduce two more classes. Each of these new classes inherits from the Car class. The process of inheritance means that all the properties and methods in the base class become part of each of the derived classes. Refer to the following code:

// RaceCar.cs
// (c) nicomp
/// <summary>
/// A derived class that inherits from the Car class
/// </summary>
class RaceCar : Car
{
}
// UsedCar .cs
// (c) nicomp
/// <summary>
/// A derived class that inherites from the Car class
/// </summary>
class UsedCar : Car 
{
}

Analysis of the derived classes

Each derived class, RaceCar and UsedCar, inherits the topSpeed and model properties of the base class, Car. The syntax for defining the base class is simple: simply reference the name of the base class, separated by a colon, on the opening line of the derived class.

Any subsequent changes made to the Car class will also be reflected in the derived classes. This illustrates a significant aspect of OOP (Object Oriented Programming): reusable and maintainable code should consist of a hierarchy of classes that trend from general to specific. In our example, the base class generally describes a 'car' and the derived classes leverage that base class to describe more specific types of cars.

Make use of the classes

In the following code fragment we add an entry point to our program. This code simply declares two instances of our derived classes and (very) briefly exercises those objects.

What may not be immediately evident to casual readers is the use of the 'get' and 'set' methods in the example code. The 'set' code is invoked in line 12, cleverly disguised as an assignment statement. C-Sharp syntax provides a mechanism for implicitly invoking 'set' methods this way. There are many OOP languages. Syntax will vary but the results will always be the same: a public method will be invoked to transfer information into the property pf the object.

Line 18 demonstrates the use of the 'get' method. The method is invoked implicitly through the reference to the symbol topSpeed. As stated previously, this syntax language specific and will vary based on the programmer's language of choice.

// main.cs
// (c) nicomp
class main
{
    /// <summary>
    /// Declare some derived class objects and illustrate their application
    /// </summary>
    /// <param name="Args"></param>
    /// <returns></returns>
    public static int Main(String[] Args)
    {
        RaceCar lotus = new RaceCar();
        UsedCar junker = new UsedCar();

        // Use the 'set' 
        lotus.topSpeed = 242;

        // Use the 'get'
        Console.Write("The top speed of our race car is ");
        Console.WriteLine(lotus.topSpeed);

        return -1;
    }
}
The output of our completed program.
The output of our completed program.

Conclusion

We have illustrated a basic example of inheritance in OOP (Object Oriented Programming) using C# (C sharp).

More by this Author


Comments 10 comments

drbj profile image

drbj 5 years ago from south Florida

Thanks for this literate information, nicomp. I use OOP constantly - just adding an 'S' when I make a boo-boo.


Derdriu 5 years ago

nicomp: Thank you for a clear, understandable presentation of this seemingly complex software concept/program. I especially appreciated the explanation of the "get" and "set" methods.

Voted up + useful + interesting


psychicdog.net profile image

psychicdog.net 5 years ago

Nicomp, why, can you tell me, did we go from procedural to OOP - does it do more, does it have less overhead or just to help model? I've often wondered this. Is it because we humans see everything as objects so programming is designed to be easy to reflect this? Would be great if you could answer this.


nicomp profile image

nicomp 5 years ago from Ohio, USA Author

@psychicdog.net: Procedural to OOP involves more overhead but facilitates a better design because software is more maintainable and some types of mistakes are reduced. We humans are amenable to thinking in terms of properties and methods for the most part.


psychicdog.net profile image

psychicdog.net 5 years ago

thanks for that Nicomp! I'm still not sold on OOP (to my detriment perhaps) and as for mistakes - commments throughout a script help reduce don't they?


nicomp profile image

nicomp 5 years ago from Ohio, USA Author

@psychicdog.net: I deduct points on programming assignments that are uncommented. I could write an epic series of hubs on comments.


Dan Smith profile image

Dan Smith 5 years ago

psychicdog.net -

One of the biggest benefits of OOP is encapsulation. Encapsulation basically means you know the what to pass into a method and what to get out, but you don't know or care about the inner workings (code) of the method.

This means that you could have a senior developer architect the the major classes and expose methods. then you can junior developers working with the classes (calling the methods) without every getting into the code of the method.

Imagine a data layer. You could have data classes responsible for fetching data from the DB. You may not want junior developers to write the SQL for performance reasons. So you write the data layer classes that return value objects. The junior developers can work with the value objects with every writing SQL.

Or to put it in layman terms, imagine you want to build your own desktop computer. You are a "junior developer" in that you are not a engineer. If you build your computer using OOP, you go buy an internal hard drive. You don't need to know exactly how it works, like the position of the internal laser. You just need to know what the "interface" is. Similarly, you buy a power transformer, PCI cards, etc. with knowing how they work. But you are capable of plugging them altogether to get them to work. Thus you build your computer with all these encapsulated components.


nicomp profile image

nicomp 5 years ago from Ohio, USA Author

@Dan Smith : Encapsulation is a major feature of OOP. Thanks for commenting.


psychicdog.net profile image

psychicdog.net 5 years ago

thanks Dan, for that - I see what you mean - many of the CMSs out there would operate like this I imagine - it makes things easier, more efficient and safer for the overall script - you want experienced engineers (not a horse for example see Nicomp's pic! LOL) to write the architecture and methods that spit out the objects - like you say passing values back is probably more efficient especially when DB queries need to be optimized for performance and to minimize bugs - leave this to the inner core team unless it was open source free for all!


Namita 5 years ago

your article is really good in c#. i love this article i have a little problem in inheritance but after reading you article it go away man. thanks buddy keep serving us . can you give the tutorial how to convert voice to text . this will help me cz i am doing a project on c#.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working