Wednesday, 14 June 2017

Encapsulation, Inheritance and Polymorphism in Object Oriented Programming

These three concepts are sometimes considered as the building block of Object Oriented Programming(OOP).


Encapsulation


Encapsulation is a construct in OOP that allows both the object and the operations performed on that object (methods) to be bundled into a class and restricts access to the methods of the class.

When a class is defined, it is normally made up of properties and methods. The properties refers to the attributes of the class while the method are the operations that can be carried out on the object.
Lets take for example, a class called Person, defined as follows:

public class person 
{
     private string Firstname;
     private string Fastname;
     private datetime DateOfBirth;

     protected Age;

     public datetime getDateOfBirth()
     {
        return person.DateOfBirth;
     }
}

In the example above class definition, the person class have been defined with four attributes, Firstname, Lastname, Age and DateOfBirth.

The class have a method GetDateOfBirth() which returns the Date of Birth of the person.
In the person class, encapsulation is achieved by the used of the keywords, private, public and protected.

The public keyword
This keyword allows makes the method or attribute accessible both from inside and outside the class.

The private keyword
Attributes and methods declared as private can only be accessible by methods inside the class. They can't be accessible by external classes.

The protected Keyword
Attributes declared as protected can be accessed by from within the  class and is also accessible by derived from that class.


Inheritance


Inheritance is an OOP concept that allows us to define a class bases on another class. So if two two object have similar attributes and one have been defined, the second object can inherit from the first one.
This concepts make it easy to reuse existing code as well as reduces the size of code to be written. So when creating a new class, the programmer need not write completely new data members and functions, the programmer can designate the class to inherit attributes and functions of an existing class. Here the existing class is called the bases class and the new class that inherits the attributes is called derived class.

The code below implemented in C# illustrates the concept of inheritance:

//This is the base class
class Shape
{
    protected int width;
    protected int height;

    public void setWidth (int w)
    {
        width = w;
    }
    public void setHeight (int h)
    {
        height = h;
    }    
}


//This is the derived class
class  Triangle : Shape  //Triangle has Shape as the base class
{
    public getArea()
    {
         return (1/2 * width * height);
    }
}

In the first class, Shape, the width and the height have is declared as protected, which means that they can be accessed by classes derived from it.

The second class, Triangle does not have attributes of width and height but is meant to derive these properties from the base class, Shape

The syntax for defining a derived class is

class <derived_class> : <base_class>



Polymorphism


Polymorphism in Programming is a feature that allows an entity to have many forms. So a function is polymorphic if it can be applied on various types.
There are three types of polymorphism, namely:

Ad hoc Polymorphism: In this type the same function perform different operations depending on the type of argument supplied.
This is also called function overloading or operator overloading. We can illustrate this using the code fragment below:

class Demo
{
   public void Add(int x, int y) // Performs integer addition
   {
       int result = x + y
       Console.Writeln(result);
   }
}

   public Add(string s, string t) //Concatenates the two strings
   {
       string result =  s.Concat(t);
       Console.Writeln(result);
   }
}

From the above class Demo, we see that two functions have been defined both having the same name. So the question would be: which of the definitions would be used when a call to this function is made? The function that would be called would depend on the parameters that are passed in at run time. If integer parameters are given at run time, then the first Add function is called which adds the two numbers together and displays the result. If however, two strings are passed in as parameter, the second function is called which concatenates the two strings and finds the result.


Parametric Polymorphism: Here, a function or data type is written generically such that it can handle values uniformly irrespective of their types. A function is a polymorphic function if it can evaluate or be applied to different types.

Subtyping: This is also called Subtype Polymorphism or inclusion polymorphism. This is when a method name denotes instances of different classes related by a base class. This is the most common type of polymorphism.

The code fragments below illustrates this various types of polymorphism.

public class Shape
{
public in x {get; set;}
public int y { get; set;}
public height {get; set}
public width {get; set}

public virtual void Render() //This is a virtual method
   {
      Console.Write("Initializing drawing tasks...");
   }
}

The above class is the base class, Shape. Other classes would derive from this class for instance, Triangle, Rectangle, Circle, Square etc.
Note that the class method Draw have been declared as virtual. This means that if a class is derived from this base class, the derived class can also have a method with the same name and this method in the derived class can provide a definition that overrides the method in the base class.

About Virtual Methods
A derived class can override a base class member only if the base class member have been declared as virtual or abstract. The derived member must use the override keyword to show that the method should override the one in the base class.

Virtual methods allow you to work with a number of related objects. So if we have a drawing application that have a base class Shape and a number of derived classes for particular shapes, then you may not know at the compile time which specific type of shape the user will create. This means that when the Draw method is invoked on a shape, the definition would be based on the particular shape it is being invoked on and this is determined at run time.

The code below gives example of some derived classes from the base class, Shape.

The code below is the derived class for Triangle

// Derived class for Triangle
class Triangle : Shape
{
   public double Area()
   {
      return height * width;
   }
   public override void Draw()
   {
      Console.WriteLine("Drawing a Triangle");
      base.Draw():
   }
}

The code below is the derived class for Circle

// Derived class for Circle
class Circle : Shape
{
   private int radius
   public double Area()
   {
      return 22/7 * radius * radius;
   }
   public override void Draw()
   {
      Console.WriteLine("Drawing a circle");
      base.Draw():
   }
}

The code below is the derived class for Rectangle

// Derived class for Rectangle
class Rectangle : Shape
{
    public double Area()
    {
       return width * height;
    }

   public override void Draw()
   {
      Console.WriteLine("Drawing a Rectangle...");
      base.Draw():
   }
}

In the three derived classes above, we see that even though the base class of Shape have a function for Draw, each of the derived classes also defines a function Draw. The Draw function in the derived classes have been declared with the override keyword and this is to indicate that the method would be used instead of the method in the base class.