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!

No comments: