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

Saturday, March 10, 2012

Polymorphism via Interfaces

In previous post we discussed polymorphism via abstraction. Today, we will discuss polymorphism via interfaces. The concept is similar except that here you declare an interface with a signature which you will then implement in one or more derived class

Consider a base employee interface with signature and then you create a full time and part time employee classes that inherit from this interface.

Interface
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Polymorphism
{
    interface iEmployee
    {
        
        void PrintEmployee();
        
    }
}


Derived Class 1

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

namespace Polymorphism
{
    class FullTime : iEmployee
    {
        public int employeeID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmployeeType { get; set; }
        public string OverTime { get; set; }
        public string VacationDays { get; set; }

        // a method signature declared in interface is implemented here
        void iEmployee.PrintEmployee()           {
            Console.WriteLine("Employee Type={0}, OverTime={1}, VacationDays{2}",
                              EmployeeType, OverTime, VacationDays);
            Console.WriteLine(Environment.NewLine);
        }
    }
}


Derived Class 2

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

namespace Polymorphism
{
     class PartTime:iEmployee
    {
        public int employeeID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmployeeType { get; set; }
        public string OverTime { get; set; }
        public string VacationDays {get;set;}
  
       // a method signature declared in interface is implemented here
        void iEmployee.PrintEmployee() 
        {
            Console.WriteLine("Employee Type={0}, OverTime={1}, VacationDays{2}", 
                              EmployeeType, OverTime, VacationDays);
            Console.WriteLine(Environment.NewLine);
        }
      public void Print()
        {
            Console.WriteLine("Employee Type={0}, OverTime={1}, VacationDays{2}", 
                              EmployeeType, OverTime, VacationDays);
            Console.WriteLine(Environment.NewLine);
        }

    }
}



As you can see, a method signature "PrintEmployee" is implemented in derived classes. A class can implement one or more interfaces and must implement the method signatures declared in each interface.

You can use the above classes as follows. Notice since the method PrintEmployee is declared in an interface, you cannot use it like you would if it was declared in a class. Since both PartTime and FullTime implement iEmployee, you should be able to cast the classes to iEmployee and then call PrintEmployee method.

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

namespace Polymorphism
{
    class Program
    {
        static void Main(string[] args)
        {
            PartTime Emp1 = new PartTime();
            //notice this property is declared in base class but available in derived class.
            Emp1.employeeID = 1234;
            Emp1.FirstName = "Part Time";
            //notice this property is declared in base class but available in derived class.
            Emp1.LastName = "Employee";
            Emp1.EmployeeType = "Part Time";

            iEmployee Emp = Emp1;
            Emp.PrintEmployee();

            FullTime Emp2 = new FullTime();
            //notice this property is declared in base class but available in derived class.
            Emp2.employeeID = 5678;
            Emp2.FirstName = "Full Time";
            //notice this property is declared in base class but available in derived class.
            Emp2.LastName = "Employee";
            Emp2.EmployeeType = "Full Time";

            Emp = Emp2;
            Emp.PrintEmployee();

            Console.ReadLine();
        }
    }
}

This is a basic concept but interfaces could be confusing. Hope this helps you understand the concept.

Thank you.



Thursday, March 8, 2012

Polymorphism via Abstraction

In previous post we discussed polymorphism via inheritance. Today, we will discuss polymorphism via abstraction. The concept is similar except that here you declare an abstract class as a base class with an abstract method which you will then implement in one or more derived class

Consider a base employee class with few properties and then you create a full time and part time employee classes that inherit from the employee class.

Base Class

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

namespace Polymorphism
{
    abstract class Employee
    {
        
        public abstract void PrintEmployee();
        
    }
}


Derived Class 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Polymorphism
{
    class FullTime:Employee
    {
        public string EmployeeType { get; set; }
        public string OverTime { get; set; }
        public string VacationDays {get;set;}
  
       public override void PrintEmployee()
        {
            Console.WriteLine("Employee Type={0}, OverTime={1}, VacationDays{2}", 
                              EmployeeType, OverTime, VacationDays);
            Console.WriteLine(Environment.NewLine);
        }
    }
}



Derived Class 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Polymorphism
{
    class PartTime:Employee
    {
        public string EmployeeType { get; set; }
        public string OverTime { get; set; }
        public string VacationDays {get;set;}
  
       public override void PrintEmployee()
        {
            Console.WriteLine("Employee Type={0}, OverTime={1}, VacationDays{2}", 
                              EmployeeType, OverTime, VacationDays);
            Console.WriteLine(Environment.NewLine);
        }
    }
}



As you can see, base abstract method "PrintEmployee" is implemented in derived classes. You can declare a method signature with keyword abstract or yon can declare a fully implemented method and use it in derived classes.

If you want to implement a method like we did here, you must declare the method with keyword "abstract" in base class and use keyword "override" in derived class.

This is a very basic concept but could be confusing for someone new to object oriented programming paradigm. Hope this helps you understand the concept.

In future post we will discuss polymorphism via interfaces.

Thank you.



Tuesday, March 6, 2012

Polymorphism Via Inheritance

In one of my post  we discussed four basic tenets of Object Oriented Programming. Polymorphism is one of the key fundamental of OOP. Polymorphism means many forms - in other words an object can take on many forms based on its implementation details. There are several ways you can implement polymorphism such as via inheritance, via interface or via abstract classes. We will discuss polymorphism via inheritance today.

Consider a base employee class with few properties and then you create a full time and part time employee classes that inherit from the employee class.

Basically you are declaring a base class with some parameters/features and then extending it into the derived classes by either modifying the base functionality or adding class specific features.

Base Class

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

namespace Polymorphism
{
    class Employee
    {
        public int employeeID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public virtual void PrintEmployee()
        {
            Console.WriteLine("EmployeeID={0},Employee Name={1}, {2}", 
                              employeeID,LastName, FirstName);
            Console.WriteLine(Environment.NewLine);
        }
    }
}


Derived Class 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Polymorphism
{
    class FullTime:Employee
    {
        public string EmployeeType { get; set; }
        public string OverTime { get; set; }
        public string VacationDays {get;set;}
  
       public override void PrintEmployee()
        {
            base.PrintEmployee();
            Console.WriteLine("Employee Type={0}, OverTime={1}, VacationDays{2}", 
                              EmployeeType, OverTime, VacationDays);
            Console.WriteLine(Environment.NewLine);
        }
    }
}



Derived Class 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Polymorphism
{
    class PartTime:Employee
    {
        public string EmployeeType { get; set; }
        public string OverTime { get; set; }
        public string VacationDays {get;set;}
  
       public override void PrintEmployee()
        {
            base.PrintEmployee();
            Console.WriteLine("Employee Type={0}, OverTime={1}, VacationDays{2}", 
                              EmployeeType, OverTime, VacationDays);
            Console.WriteLine(Environment.NewLine);
        }
    }
}



As you can see, base virtual method "PrintEmployee" is extended in derived classes. Properties declared in the base class are available to derived classes.

If you want to extend a method like we did here, you must declare the method with keyword "virtual" in base class and use keyword "override" in derived class.

This is a very basic concept but could be confusing for someone new to object oriented programming paradigm. Hope this helps you understand the concept.

In future posts we will discuss polymorphism via interface and abstract classes.

Thank you.



Thursday, March 1, 2012

C# Delegates

The concept of delegates is somewhat confusing and developers often wonder why we need them and where would we use delegates? We will discuss delegates with an example and hopefully clarify potential uses for them.

Consider a list object of a specific type. You can encapsulate one or more objects of the same type in this list and pass the list to other methods to read and do something with those objects. Delegates are similar in nature except that they encapsulate references to the methods of an object.

A delegate can encapsulate any method as long as method signatures are same as those of delegates. Use can then pass around those delegates or use them just as you would use the method encapsulated in those delegates.

Let's consider an example.

In this example, we will create a class which will take the hourly pay, hours worked, tax rate and return weekly pay as well as tax.

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

namespace ConsoleApp1
{
    class CalculateWeeklyPay
    {
        private double _hourlypay;
        private double _hours;
        private double _overtimerate;
        private double _taxrate;

   public CalculateWeeklyPay(double hourlypay, double hours, 
                             double overtime, double taxrate)
        {
            _hourlypay = hourlypay;
            _hours = hours;
            _overtimerate = overtime;
            _taxrate = taxrate;
        }
        public double calculateTax()
        {
            double grosspay = calculateGrossPay();
            double tax = grosspay * ((double)_taxrate / 100);
            return tax;
        }
  public double calculatePay(double hourlypay, double hours, 
                             double overtime, double taxrate)
        {
            _hourlypay = hourlypay;
            _hours = hours;
            _overtimerate = overtime;
            _taxrate = taxrate; 
            return calculatepay();
        }
        public double calculatePay()
        {
            return calculatepay();
         }
        private double calculatepay()
        {
            double grosspay = calculateGrossPay();
            double netpay = grosspay-(grosspay * ((double)_taxrate / 100));
            return netpay;
        }
        private double calculateGrossPay()
        {
            double basepay;
            double overtimepay = 0;
            double grosspay;
            
            if (_hours > 40)
            {
                overtimepay = (_hours - 40) * (_hourlypay * _overtimerate);
                basepay = 40 * _hourlypay;
            }
            else
            {
                basepay = _hours * _hourlypay;
            }
            grosspay = basepay + overtimepay;
            return grosspay;
        }
     }
}

Now, lets create a console app, which will instantiate this object and then return the weekly pay and tax. We will create two delegates. One delegate will work with two methods (CalculatePay and CalculateTax) and another delegate will work with overloaded CalculatePay method.

Note, a delegate must have the same signature and same return type of the referenced method that it will encapsulate.

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

namespace ConsoleApp1
{
    class Program
    {
        //declared two deletages, one for each method
        //(since they have different signatures, you can't use same delegate)
        //also note return type for the delegate 
        //must be same as the return type of the signature.
        public delegate double delegate1();
        public delegate double delegate2(double hourlypay, double hours, 
                                         double overtime, double taxrate);
      
           
        static void Main(string[] args)
        {
            double hourlyPay = 7.50;
            double hours = 45;
            double overtimeRate = 1.5;
            double taxRate = 5;
          CalculateWeeklyPay calculatepay = new CalculateWeeklyPay(hourlyPay, 
                                                 hours, overtimeRate, taxRate);
            //you must instantiate a delegate
            delegate1 firstDelegate = new delegate1(calculatepay.calculatePay);
            Console.WriteLine("First Delegate {0} ", firstDelegate());
            Console.WriteLine(Environment.NewLine);
            //you can use same delegate for another method as long as 
            //its signatures and return type are same
            delegate1 anotherDelegate = new delegate1(calculatepay.calculateTax);
            Console.WriteLine("First Delegate Different Use {0} ", 
                              anotherDelegate());
            Console.WriteLine(Environment.NewLine);
            //let's use second delegate
            delegate2 secondDelegate = new delegate2(calculatepay.calculatePay);
            //you must pass the parameters that this delegate is expecting, 
            //otherwise a runtime error will occur
            Console.WriteLine("Second Delegate{0} ", 
                       secondDelegate(hourlyPay, hours, overtimeRate, taxRate));
            Console.WriteLine(Environment.NewLine);
            Console.Read();
        }
    }
}


One of the main use of delegates is in events. Suppose you want an object to notify another object when something happens. For example, a stock market object should fire an event when stock price changes for a stock you are watching. Another object (listener) can capture this event and do something with it instead of constantly polling the stock market object to see if the price has changed. In C#, you need delegates to create events such as this.

We will discuss events in future posts.

Thank you.

Tuesday, February 7, 2012

Fundamentals of Object Oriented Programming

All Programming Fundamentals!
Any interview I have been in, either as a interviewer or interviewee, a question about Object Oriented Programming has always come up. Almost always the question is stated as follows...
What are the basic principles of Object Oriented Programming or what are the tenets of Object Oriented Programming.
The answers vary from person to person. Most of the developers with some experience in OOP know what they were talking about, but struggle in putting their answers in words. So, I decided to go ahead and describe what I understand them to be. Keep in mind, these are not the only definitions.
Basically in a nutshell, there are four basic tenets or core principles of Object Oriented Programming.
    • Abstraction
    • Data Encapsulation
    • Inheritance
    • Polymorphism
Abstraction
Abstraction allows for simplicity. As a consumer you do not need to worry about all the implementation details that go in whatever it is you are consuming. For example, when you turn the radio in your car, you mainly care about volume, channel, and a few other items. You don't need to worry about how the radio works and receives the programming over the air. In the world of programming, abstraction is a similar concept. A class could be implemented in various ways, but the consuming application doesn't have to worry about all the intricate details. All the consumer has to know is the public face of the class to use that class and get the expected results back. For example, if you want to generate an invoice for a customer at the end of the month, you will simply pass on customer information, invoice period and expect the class to return you the results back. How the class gathers the data, communicates with other classes or database etc. is of no concern to you.
Abstraction allows for modular code development and code reuse. Same class can be used by various calling methods without having to worry about the class and its implementation details.
Data Encapsulation
Data Encapsulation is simply what the name suggests. All the relevant data is encapsulated within the class. The calling object never has to worry about how the data is manipulated within the callee, only that the data is returned back in the format it was expected. Encapsulation is implemented by classifying certain properties and methods as public and the outside world can only communicate via only those public methods/properties. For example, in an Employee class, you may declare a public property called "Employee Name" as of type String. The caller will expect and will get a string back. How the Employee class assembles the Employee Name to return back to the caller is of no concern to the caller.
Inheritance
Inheritance allows for abstracting certain common characteristics of an entity in a way that multiple entities that exhibit those same characteristics can "inherit" from the common entity without having to declare them. Inheritance is a "Type Of" or "Kind Of" relationship. For example, An Audi is a type of Car. A BMW is a type of Car. A male and a female are a "Type Of" person. Basically what that means is that both Audi and BMW will exhibit certain common characteristics that all cars have. Similarly both male and feamle will exhibit certain characteristics that are common to all persons.
With this understanding, we can define a class called "Car" and a class called "Person" and have "Audi" and "BMW" classes inherit from "Car" and "Male" and "Female" classes inherit from "Person" class. This will allow us to promote some properties to higher level classes that would otherwise have to be defined in each class.
Polymorphism
Polymorphism, when used correctly enables tremendous code reuse. Polymorphism can be used at the class/object level or at the method level. The most common use I have seen is at the method level. At the method level, it manifests itself either in method overriding or method overloading. Method overloading means you can create two or more methods with the same name but with different signature. Method Overriding means you can declare a method in a base class, make it overridable and then override it in individual classes that inherit from the base class. Method Overloading is also called compile time polymorphism because compiler determines which overloaded method to use during compile time. Method Overriding is also called run time polymorphism because which method will be used is determined at run time.
Object level or inheritance level polymorphims occurs when a method is implemented in base class and all the derived classes use the same implementation. For example, you are writing a stream to either file or memory or network location. All the various stream options are implemented in their own class, but they all inherit from the base class called "Stream" and "Serialize" method is implemented in this base class. All the derived classes will be able to use the same "Serialize" method without having to create their own.
There is much more to Object Oriented Programming and indeed even to these 4 basic tenets, but hopefully this will help you get started!

We will be discussing more about Object Oriented Fundamental in the future.
Thank you and your comments are welcome!