Inheritance in C#

Posted on Updated on

Image result for Inheritance in C#Inheritance in C#

Inheritance is one of the building blocks of any object oriented programming. The inheritance is the ability to create classes which inherits certain aspects from parent class. The entire .NET framework is built on this concept, with the “everything is an object”. All the classes in c# are inherited from System. Object class.

Inheritance enables to create a new class that reuse, extend and modify the behavior that is defined in other classes. The class whose members are inherited or reused are called as base class/ parent class/ super class. The class that inherits the features of the parent class is called derived class/ child class/ sub class. A derived class can have only one direct base class. It is transitive in nature i.e. If ClassC is derived from ClassB, ClassB is derived from ClassA, thenClassC can directly access the members of ClassA and ClassB.

Inheritance implements the IS-A relationship i.e. a derived class is specialization of the base class. For example there is a base class Animal and Dog & Cat are the derived classes of the Animal class. Then we can say that Dog is-aAnimal, Cat is-a Animal but each derived class represents the different specializations of the base class.

Derived class implicitly gains all the members of the derived class except the constructors and destructors.

The following figure shows a class Work Item that represents an item of work in some business process. Just like all other classes, it is also derived from System. Object and inherits all its methods. Work Item adds five members of its own. They include a constructor, because constructors are not inherited. Class Change Request is inherited from Work Item and represents a particular kind of work item. Change Request adds two more members to the members that it inherits from Work Item and from Object. It must add its own constructor, and it also adds original Item ID. Property original Item ID enables the Change Request instance to be associated with the original Work Item to which the change request applies.

The following example shows how the class relationships demonstrated in the previous illustration are expressed in C#. The example also shows how WorkItem overrides the virtual method Object.ToString, and how the ChangeRequest class inherits the WorkItem implementation of the method.

//WorkItem implicitly inherits from the Object class.

publicclassWorkItem

        {

//Static field currentID stores the job ID of the last WorkItem thathas been created.

privatestaticintcurrentID;

//Properties.

protectedint ID { get; set; }

protectedstring Title { get; set; }

protectedstring Description { get; set; }

protectedTimeSpanjobLength { get; set; }

// Default constructor. If a derived class does not invoke a base-class constructor explicitly, the default constructor is calledimplicitly.

publicWorkItem()

            {

                ID = 0;

                Title = “Default title”;

                Description = “Default description.”;

jobLength = newTimeSpan();

            }

// Instance constructor that has three parameters.

publicWorkItem(string title, stringdesc, TimeSpanjoblen)

            {

this.ID = GetNextID();

this.Title = title;

this.Description = desc;

this.jobLength = joblen;

            }

// Static constructor to initialize the static member, currentID. Thisconstructor is called one time, automatically, before any instance

ofWorkItem or ChangeRequest is created, or currentID is referenced.

staticWorkItem()

            {

currentID = 0;

            }

protectedintGetNextID()

            {

// currentID is a static field. It is incremented each time a newinstance of WorkItem is created.

return ++currentID;

            }

// Method Update enables you to update the title and job length of anexisting WorkItem object.

publicvoid Update(string title, TimeSpanjoblen)

            {

this.Title = title;

this.jobLength = joblen;

            }

// Virtual method override of the ToString method that is inheritedfrom System.Object.

publicoverridestringToString()

            {

returnString.Format(“{0} – {1}”, this.ID, this.Title);

            }

        }

// ChangeRequest derives from WorkItem and adds a property (originalItemID)and two constructors.

publicclassChangeRequest : WorkItem

        {

protectedintoriginalItemID { get; set; }

// Constructors. Because neither constructor calls a base-class

// constructor explicitly, the default constructor in the base classis called implicitly. The base class must contain a default constructor.

// Default constructor for the derived class.

publicChangeRequest() { }

// Instance constructor that has four parameters.

publicChangeRequest(string title, stringdesc, TimeSpanjobLen,

intoriginalID)

            {

// The following properties and the GetNexID method are inherited from WorkItem.

this.ID = GetNextID();

this.Title = title;

this.Description = desc;

this.jobLength = jobLen;

// Property originalItemId is a member of ChangeRequest, but not of WorkItem.

this.originalItemID = originalID;

            }

        }

class Program

        {

staticvoid Main()

            {

// Create an instance of WorkItem by using the constructor in the base class that takes three arguments.

WorkItem item = newWorkItem(“Fix Bugs”,”Fix all bugs in my code branch”,newTimeSpan(3, 4, 0, 0));

// Create an instance of ChangeRequest by using the constructor in the derived class that takes four arguments.

ChangeRequest change = newChangeRequest(“Change Base Class Design”,”Add members to the class”,newTimeSpan(4, 0, 0),1);

// Use the ToString method defined in WorkItem.

Console.WriteLine(item.ToString());

// Use the inherited Update method to change the title of the

// ChangeRequest object.

change.Update(“Change the Design of the Base Class”,

newTimeSpan(4, 0, 0));

// ChangeRequest inherits WorkItem’s override of ToString.

Console.WriteLine(change.ToString());

// Keep the console open in debug mode.

Console.WriteLine(“Press any key to exit.”);

Console.ReadKey();

            }

        }

/* Output:

            1 – Fix Bugs

            2 – Change the Design of the Base Class

        */

*****************************************************************************************************

For more details and queries please feel free to email, visit or call us. Wishing you the very best for all your future endeavors.
Helpline: 9814666333, 8699444666
Email: info@technocampus.co.in

Please fill the form and we shall contact you soon.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s