Thursday, April 12, 2007

A brief look at "inheritance" and how to "inherit"...

What is inheritance?


In previous years of programming the developer would often create a class that would contain specific members (properties and methods). When the developer wanted to create another class that would cater to different specific needs, even if they needs were similar in many areas with enough differences to not allow use of the first class, the developer would need to create another class, including all of the members, to fill these needs. 


As Object-Oriented Programming (OOP) had caught on the idea of the ability to re-use code was a major benefit of this new concept. To enable to developer to avoid from having to recreate a class with minor changes Microsoft (and other language specific providers) had introduced the idea of “inheritance” of classes. A developer could create a second class (the derived class) based on the first class’ (base class) members. In many cases the derived class would have proven error-free methods and properties the developer would want to bring into the derived class. The developer was then given the option to use “inheritance” of the base class in the derived class. The developer would then be able to pick and choose what members the derived class would be allowed to have access to, as well as what members the derived class would utilize.  


Another nice feature was that the developer could create a derived class from the original derived class, any inherited members of the derived (second derived) classes are considered to be “indirect base class” inheritances. The inheritances found in the first derived class are class “direct base class” inheritances.


How do you inherit?


To derive a class you simply follow the class identifier with a colon and then the name of the base class. 


Figure 1 shows the creation of the base class called “Base_Patient.cs”:






using System; 


namespace inheritance_1
{
    public class Base_Patient
    {
        public string strFirstName,
            strLastName; 


        // default values constructor class
        public Base_Patient() { } 


        // preferred constructor method
        public Base_Patient(string strFN, string strLN)
        {
            strFirstName = strFN;
            strLastName = strLN;
        } 


        //destructor of object class
        ~Base_Patient() { } 


        //property firstName of patient
        private string FirstName
        {
            get
            {
                return strFirstName;
            }
            set
            {
                strFirstName = value;
            }
        } 


        //property lastName of patient
        private string LastName
        {
            get
            {
                return strLastName;
            }
            set
            {
                strLastName = value;
            }
        } 


        //Displaying patient's name (last, first)
        public void DisplayName()
        {
            Console.WriteLine("The patient's name is " + strLastName + ", " + strFirstName + ".");
        } 


    }//end class
}//end namespace

Figure 1 (Base class "Base_Patient.cs")

Figure 2 shows the creation of the derived class called “Derived_Patient.cs”:






using System;
using System.Collections.Generic;
using System.Text; 


namespace inheritance_1
{
    //The following line of code inherits from the base class called "Base_Patient"
    class Derived_Patient : Base_Patient 
    {
        //Here we are just declaring a new variable that will be used in the class
        //this variable can also be called from outside objects and classes
        public string strMiddleName; 


        //Here we create our constructor for the derived class
        //notice we don't have to recreate the constructors for the
        //base class as we have 'inherited' that constructor method.
        public Derived_Patient(string strMN, string strFrstN, string strLstN)
        {
            //The only requirement we have to utilize the properties that
            //have already been created in the base class is to create
            //assigments of values to the variables. In the instances where
            //the values were previously assigned in the base class this
            //inherited class would already have them stored and we would
            //not need to assign a value, unless we wanted to overrite that
            //value with one from this class. NOTE: Assigning a new value here
            //would not replace the base class value, it would only be creating
            //the value in this class reference and this class would only see
            //that new reference (and any derived classes of this derived class).
            strMiddleName = strMN;
            strFirstName = strFrstN;
            strLastName = strLstN;
        } 


        //Here we created our destructor of the class
        ~Derived_Patient() { } 


        //Here we are creating the property and the method of setting / getting
        //the values of that property. Notice we have declared the property method
        //as private. This will ensure that no outside calls can modify this
        //property without going through our pre-defined constructor class. This is
        //a best practice method because we are controlling access to the property.
        private string MiddleName
        {
            get
            {
                return strMiddleName;
            }
            set
            {
                strMiddleName = value;
            }
        } 


        //Here I am creating a simple console writing statment that will display
        //our middle name along with the First and Last name of the base class
        //we had inherited.
        //Notice in particular the references to the "strFirstName" and "strLastName"
        //properties that were defined in the base class; we did NOT need to do one
        //line of coding to utilize these properties!!!
        public void DisplayFullName()
        {
            //This writes to the console
            Console.WriteLine("The patients FULL name is: " + strFirstName + " " + strMiddleName + " " + strLastName);
        }


    }//This ends class
}//This ends the namespace

Figure 2 (Derived class "Derived_Patient.cs")

Figure 3 shows the creation of the “Program.cs”:






using System;
using System.Collections.Generic;
using System.Text;


namespace inheritance_1
{
    class Program
    {
        static void Main(string[] args)
        {
            //The following 2 lines of code will demonstrate how to create objects of
            //the derived class and the base class. You will want to pay attention that
            //I had intentionally created the derived class object first to show you that
            //when I create the base class information it does not overwrite the derived
            //class' information. The order of calling methods does not matter in this
            //case because each object occupies its own memory resource and can fully
            //function independently.
            Derived_Patient clsDerivedPatient = new Derived_Patient("Edward", "John", "Smith");
            Base_Patient clsBasePatient = new Base_Patient("Jane", "Doe"); 


            //The following lines of code will demonstrate how to call the methods from
            //within the derived class and base class. You will want to pay attention that
            //I am intentionally calling the derived class first to show that even though
            //the last line of code ABOVE had called and written to the property of the
            //base class' "First Name" and "Last Name" that the derived class' properties
            //were not overwritten. The order of calling methods does not matter in this
            //case because each object occupies its own memory resource and can fully
            //function independently.
            Console.WriteLine("This is to display the derived class' information...");
            clsDerivedPatient.DisplayFullName();
            Console.WriteLine();
            Console.WriteLine("This is to display the base class' information...");
            clsBasePatient.DisplayName();
            Console.ReadLine(); 


            //You can feel free to move the lines of code around in your own implementation
            //of this code example. You will see that regardless of what order you place the
            //lines of coding you will get the same results; with exception, of course, of
            //the results being displayed in different order if moved to a different order
        }

    }//This ends the class
}//This ends the namespace

Figure 3 (Main program "Program.cs")

You can see from above an example of how you can inherit from another class and how you can still use the base class’ members. The main point to understand here is that when you inherit from a class you are not necessarily overwriting that class; there are other keyword modifiers that can be used with the creation of classes that can force the developer to overwrite a class’ member, and likewise there are keyword modifiers that can prevent a developer from overwriting a class’ member. 


The next blog will touch on “polymorphism”; which is one of the methods used to define or redefine the base class’ members (typically methods). 


Hopefully this will help you to grab a good grasp on inheritance and how to inherit from a class. Remember that trial and error are the best way to learn in programming, regardless of the amount of books and blogs you read or classes you take trying out what you learn will surpass in learning experiences. Written forms can only tell you so much, so please try what you learn and always change things around and try out ideas. I find it enjoyable to think of a new thing I want to see if I can do and just start coding it in and see where my ideas fall short at and how to make them work in the real world. 


Happy coding!

No comments: