Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts

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!

Wednesday, April 11, 2007

A brief look at classes and how to use them...

What are classes?



Classes are a collection of unlike data and functions. Quite simply put; classes can hold string, integers, double, Booleans and other types of data in one bundled location.



An example would be if you were to create an application for a doctor’s office to hold patient information. Some basic information each patient may be required to supply is their first name, last name, age, medical group number, if they are a minor.



A class would hold all of this information. Each person’s information would be placed into a class through the use of an object. An object, in this instance, would be thought of as the person themselves. Each person would tell the class what their information is (we will cover this in more detail in a future blog about objects).



How do you use classes?



An example of how you would build a simple class to hold the persons information would be:



First I created a class file called “Base_Patient.cs” and placed the following code in it:





//This line of coding will implement the classes within
//the "System" framework. This implementation is created
//by using the keyword "using". We implement "System" so
//we may use the "Console" class. We can avoid implementing
//the "System" class by calling the "Console" class directly
//through the framework it is stored within.
using System; 

namespace myDoctors_Application
{
    public class Base_Patient
    {
        //patient attributes (2 strings, 2 integers, 1 boolean)
        //Here we are declaring these variable public so classes
        //and method calls from outside this class can access
        //them. If we have a variable we wish not to be modified 
        //outside of this class we would then declare it as "private"
        public string strFirstName,
            strLastName;

        public int intAge,
            intMedicalGroup;

        public bool blnIsMinor; 


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


        // preferred constructor method
        //This constructor class shall place all variables
        //provided to it in our instance of the class. You
        //can see in the subsequent lines of code in this
        //constructor that we are matching the appropriate
        //variable in the constructor's argument list
        //to the appropriate variable we had previously
        //declared as public (or we could have made private
        //if we didn't want the variable’s value leaving this class).
        public Base_Patient(string strFN, string strLN, int intA, int intMGN, bool blnM)
        {
            strFirstName = strFN;
            strLastName = strLN;
            intAge = intA;
            intMedicalGroup = intMGN;
            blnIsMinor = blnM;
        } 


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


        //The all of the following property methods just set
        //and get the appropriate variables.
        //This should be self explanatory. 


        //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;
            }
        } 


        //property Age of patient
        private int Age
        {
            get
            {
                return intAge;
            }
            set
            {
                intAge = value;
            }
        } 


        //property MedicalGroupNumber of patient
        private int MGN
        {
            get
            {
                return intMedicalGroup;
            }
            set
            {
                intMedicalGroup = value;
            }
        } 


        //property IsMinor 
        private bool Minor
        {
            get
            {
                return blnIsMinor;
            }
            set
            {
                blnIsMinor = value;
            }
        } 


        //The following methods show that you can choose
        //to have your base class perform lines of code
        //and return the results to the calling object class. 


        //Displaying the patient's age
        public void DisplayAge()
        {
            //This was written this way to show you how to
            //use an inner-joining concatenation for strings and
            //variables. The "+" is our concatenation operator.
            Console.WriteLine("This patient is " + intAge + " years old.");
        } 


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


        //Display if patient is a minor
        public void DisplayIsMinor()
        {
            Console.WriteLine("Is this patient a minor? " + blnIsMinor);
        } 



        //Display the patients Medical Group #
        private void DisplayMedicalGroup()
        {
            Console.WriteLine("The patient's medical group # is: " + intMedicalGroup);
        } 


    }//end class
}//end namespace

Figure 1 (base class coding; “Base_Patient.cs”). 



Next I created the primary program file called “Program.cs” and paced the following code in it:





//I have commented out the declaration implementing the "System"
//class to show ways to implement the console by directly calling
//it from the class it is stored in.
//using System;
 

namespace myDoctors_Application
{
    class DerivedPatientClass: Base_Patient 
    {
        //main entry point
        static void Main(string[] args)
        {
            //This line of coding creates a new
            //object called "clsPatient"
            //it is an object derived from the base
            //class called "Base_Patient".
            //We use the "new" operator to create the object
            //and we are using the overloaded method of 
            //the constructor inside the base class.
            Base_Patient clsPatient = new Base_Patient("John", "Smith", 28, 123456, false); 

            //The following lines of code that start with
            //"Console.WriteLine" are methods that are 
            //built-in to the "System" class and will allow 
            //us to create a console window and write to the 
            //console window...you can see in the first two lines 
            //I had created a simple text that is written
            //to the console.
            System.Console.WriteLine("This is to display the patient's information we stored in our base class!");
            System.Console.WriteLine("Patient Info: "); 

            //Here I am calling the object "clsPatient"
            //that I had created earlier;
            //I am exposing the methods that were made
            //public in the class since the class methods
            //already contain code to write to the console we can
            //omit the "Console.WriteLine" method call
            //in these instances.
            clsPatient.DisplayName();
            clsPatient.DisplayAge();
            clsPatient.DisplayIsMinor(); 

            //If you uncomment the below line you will
            //recieve an error; this is because in the
            //base class this method was declared as private;
            //this means only the base class itself can use that 
            //method! To be able to display this method from the
            //base class you can go into the base class and change
            //the line from "private void DisplayMedicalGroup()"
            //to "public void DisplayMedicalGroup()" 

            //clsPatient.DisplayMedicalGroup();



            //This line of code shows that even though the “DisplayMedicalGroup()”
            //method is declared private you can still access the variable called
            //”intMedicalGroup”; you can access it because the variable was created
            //as a “public” variable. Remember that properties, methods, variables (etc..)
            //that are “public” can be read / written to from the base class and all derived
            //classes and objects. Properties, methods and variables created “private”
            //can only be accessed from within the base class that created it.
            System.Console.WriteLine("Patient is from Group # " + clsPatient.intMedicalGroup);


            //This line of code is actually meant to be used
            //to receive user input from the console window;
            //however, in this example we are simply using it
            //to pause the application from continuing to run
            //until the end-user has pressed the "ENTER"
            //key; otherwise the console window would appear
            //and disappear faster than you could read the contents
            //and verify everything is appearing as intended.
            System.Console.ReadLine(); 

        }//end Main()
    }//end class
}//end namespace

Figure 2 (main program coding; “Program.cs”). 



These examples have detailed explanation of why each line of code exists. 



The primary purpose of these examples are to show how the class is created (see Figure 1) and how you can create an object of the created class and use the methods within the class (see Figure 2). 



I would like to point out in this blog, as well as it is already commented in the coding, the use of the public and private keyword modifiers. This will be covered in more detail in a future blog. The important thing here is to realize that in the base class code the “private” keyword used with the DisplayMedicalGroup() method limits the use of this method to calls from within the base class ONLY! 



You will notice in the creation of the base class (Figure 1) that the first line of code “using System;” was included. This allows for us to call the “Console” method directly from the “System” class. We can omit this line of coding should we desire; however, this would create additional coding to be used to use the “Console” method. You can see a demonstration of how-to call the “Console” method directly from the class in the main program coding (Figure 2). 



Hopefully this has given you a decent understanding of how to initiate a class, at the base level, and call it from within your application coding (by creating an object-instance of the class). 



Happy coding!

Wednesday, April 4, 2007

What is OOP and why do you need it?

Ok, this was actually covered in fairly good detail on our sister blog site: Visual Basic Helper; however, the topic pertains to C# users as well as the VB users. Below you will find some excerpts from the original blog posting. You can view the entire posting by visiting: http://visualbasichelper.blogspot.com/2007/03/what-is-object-oriented-programming-oop.html.

Object-Oriented Programming (OOP) is a concept used for programming. It is like a different way to look at things. The basic principle of OOP is that everything is either an object, a property to the object, or a method of the object. Before we can get into why you need OOP, you need to know a few other things first.

OOP originally was designed to provide an answer to a "software development crisis" in the 1960s. The problem was as the software was beginning to become more and more complex there was no methods around to ensure the quality was maintained. Introduce Object-Oriented programming concept. The concept is that every program contains "objects" and these "objects" would have properties and/or methods. (Notice the use of "and/or"; some objects can have both, or just one or the other). Objects would also be able to 'inherit', 'polymorph', and 'encapsulate' to and from other objects.

Microsoft had finally decided that they had to make a serious effort to be competitive in the enterprise software development market. Their first major step in this effort was a huge improvement; it was the introduction of .NET! The reason this was a huge improvement was because the .NET architecture is based on OOP concepts. A prime example of this is that the entire .NET architecture is a collection of classes. Classes are the foundation of OOP! (.NET will be further explored in a future blog)

Please take a few minutes and read-up on the concepts of OOP and how to use them. If you are unsure of where to begin then there are two resources I would recommend.
Wikipedia and Google. In both cases do a search for "Object-Oriented Programming"; if you want more in-depth information than head out to your local bookstore that carries programming reference materials and pick up a book on the subject; you will find many titles available, and you will see just how vast the subject is and quickly realize the importance to learn this.

OOP will be the cornerstone of all of your programming needs and answers.