Friday, 6 May 2016

Introduction to Object Oriented Programming (OOP)


Whats is OOP?

OOP refers to a programming methodology,  instead of just functions and procedures. Most modern programming languages including c#, Java and C/C++ are object-oriented languages, and many older programming languages now have object-oriented versions.
Oop makes it easier for programmers to structure and organize software programs. Because  objects can be modified without affecting other aspects of the program.
  1.  Object
  2.  Class
  3.  Encapsulation
  4.  Abstraction
  5.  Inheritance
  6.  Polymorphism

 What is an Object?
Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle.
Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.
Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.
In pure OOP terms an object is an instance of a class.

What is a Class?
A class is a blueprint or template or set of instructions to build a specific type of object. Every object is built from a class. Each class should be designed and programmed to accomplish one, and only one, thing. 
public class Student
{
}
According to the sample given below we can say that the Student object, named objectStudent, has been created out of the Student class.
Student objectStudent = new Student();
In real world, you'll often find many individual objects all of the same kind. As an example, there may be thousands of other bicycles in existence, all of the same make and model. Each bicycle has built from the same blueprint. In object-oriented terms, we say that the bicycle is an instance of the class of objects known as bicycles.

How to identify and design a Class?
Following are the principle that you must follow when design a class :
·         SRP (The Single Responsibility Principle)
          A class should have one, and only one, reason to change.
·         OCP  (The Open Closed Principle )
          Should be able to extend any classes' behaviors, without modifying the classes..
·         LSP ( The Liskov Substitution Principle)
          Derived classes must be substitutable for their base classes.
·         DIP  (The Dependency Inversion Principle)
          Depend on abstractions, not on concretions.
·         ISP (The Interface Segregation Principle)
      Make fine grained interfaces that are client specific.

What is Encapsulation ?
Encapsulation is refers to an object's ability to hide data and behavior that are not necessary to its user. Encapsulation enables a group of properties, methods and other members to be considered a single unit or object.
 The idea of encapsulation is to hide how a class does its business, while allowing other classes to make requests of it.
Public class Student

  // Class constructor
         public student();
    // Property of Class
         public int age {get;set;}
          public string name{get;set}
     // Methods in a class
         public  DoLearn(){}
}

There are several other ways that an encapsulation can be used, as an example we can take the usage of an interface. The interface can be used to hide the information of an implemented class.
IStudent myLStudent = new LocalStudent(); 
IStudent myFStudent = new ForeignStudent();
According to the sample above (let’s assume that both LocalStudent and ForeignStudent classes have implemented the IStudent interface) we can see how LocalStudent and ForeignStudent hide their localize implementing through the IStudent interface.
As an example in both instances ‘myLStudent’ and 'myFStudent' are of type IStudent, but they both carries two separate local and foreign implementation underneath. This way a method call like 'DoLearn(object)' to 'myLStudent' and 'myFStudent' object will trigger their respective foreign and local implementation. This way 'myFStudent' carrying 'ForeignStudent' will trigger the respective learning function with foreign syllabus while the other one with 'LocalStudent' will trigger the learning function with local syllabus.

What is Association?
Association also called a "has-a" relationship that says one class is somehow associated with another class.
Let’s take an example of relationship between Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers. But there is no ownership between the objects and both have their own lifecycle. Both can be created and deleted independently.
                               Student --------------- Teacher
What is Aggregation ?

It is a specialized form of Association where all object have their own lifecycle but there is ownership. This represents “whole-part or a-part-of” relationship. This is represented by a hollow diamond followed by a line.
                                        
Let’s take an example of relationship between Department and Teacher. A Teacher may belongs to multiple departments. Hence Teacher is a part of multiple departments. But if we delete a Department, Teacher Object will not destroy.
                   
                Teacher Department
What is Composition ?
It is a specialized form of Aggregation. It is a strong type of Aggregation. In this relationship child objects does not have their lifecycle without Parent object. If a parent object is deleted, all its child objects will also be deleted. This represents “death” relationship. This is represented by a solid diamond followed by a line.
                                      
Let’s take an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room cannot belongs to two different house if we delete the house room will automatically delete.
                Room House
What is Dependency?
It represents a relationship between two or more objects where an object is dependent on another object(s) for its specification or implementation. This is represented by a dashed arrow.
                                          
Let’s take an example of relationship between client and service. A client is dependent on the service for implementing its functionalities.
                  Client Service
Let’s take another example of relationship between a client and a supplier. A client is dependent on the supplier for supplying products. If the supplier will not supply the products, client cannot use those products.

What is Abstraction and Generalization?
 Abstraction :
Abstraction is the process of showing the essential details or features of an object and hiding its  complexity.                                         
                
In the above figure, for same Cat , from  the view point of  lady(cat owner), she see it as a sweet little cute cat  having 4 legs and a tail etc. but from the view point wetnary surgeon the cat has got the kidney,liver, lung etc.Thus two people have the different abstract model for the same  cat.
Generalization:
When we create a base/super class from two or more similar type of objects by extracting their all  common characteristics(attributes and behavior) and combine them, then this process is known as Generalization.
                    
Example : In the above figure the classes Book and Disk partially share the same attributes. During generalization, the shared characteristics such as Id, Price and description are combined and used to create a new super class Product. Book and Disk become sub classes of the class Product.

What is an Abstract class?
An abstract class means that, no object of this class can be instantiated, but can make derivations of this.
An example of an abstract class declaration is:
abstract class absClass
{
}

An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.
An example of an abstract method:
abstract class absClass
{
  public abstract void abstractMethod();
}
Also, note that an abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non abstract members. For example:

abstract class absClass
{
    public void NonAbstractMethod()
    {
        Console.WriteLine("NonAbstract Method");
    }
}
A sample program that explains abstract classes:

using System;

namespace abstractSample
{
      //Creating an Abstract Class
      abstract class absClass
      {
            //A Non abstract method
            public int AddTwoNumbers(int Num1, int Num2)
            {
                return Num1 + Num2;
            }

            //An abstract method, to be
            //overridden in derived class
            public abstract int MultiplyTwoNumbers(int Num1, int Num2);
      }

      //A Child Class of absClass
      class absDerived:absClass
      {
            [STAThread]
            static void Main(string[] args)
            {
               //You can create an
               //instance of the derived class

               absDerived calculate = new absDerived();
               int added = calculate.AddTwoNumbers(10,20);
               int multiplied = calculate.MultiplyTwoNumbers(10,20);
               Console.WriteLine("Added : {0},
                       Multiplied : {1}", added, multiplied);
            }

            //using override keyword,
            //implementing the abstract method
            //MultiplyTwoNumbers
            public override int MultiplyTwoNumbers(int Num1, int Num2)
            {
                return Num1 * Num2;
            }
      }
}

In the above sample, you can see that the abstract class absClass contains two methods AddTwoNumbers and MultiplyTwoNumbers. AddTwoNumbers is a non-abstract method which contains implementation and MultiplyTwoNumbers is an abstract method that does not contain implementation.
The class absDerived is derived from absClass and the MultiplyTwoNumbers is implemented on absDerived. Within the Main, an instance (calculate) of the absDerived is created, and calls AddTwoNumbers and MultiplyTwoNumbers. You can derive an abstract class from another abstract class. In that case, in the child class it is optional to make the implementation of the abstract methods of the parent class.
 What is an Interface?
Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface. Interfaces just specify the method declaration (implicitly public and abstract) and can contain properties (which are also implicitly public and abstract). Interface definition begins with the keyword interface. An interface like that of an abstract class cannot be instantiated.

If a class that implements an interface does not define all the methods of the interface, then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class. In addition to this an interfaces can inherit other interfaces.
The sample below will provide an interface for our LoggerBase abstract class.

public interface ILogger
{
    bool IsThisLogError { get; }
}
What is the difference between an Interface and an Abstract class?
There are quite a big difference between an interface and an abstract class, even though both look similar.
  • Interface definition begins with a keyword interface so it is of type interface
  • Abstract classes are declared with the abstract keyword so it is of type class
  • Interface has no implementation, but they have to be implemented.
  • Abstract class’s methods can have their own default implementations and they may be extended. The Abstract class’s methods could run independant of the inherting class.
  • Interfaces can only have method declaration (implicitly public and abstract) and properties (implicitly public static)
  • Abstract class’s methods can’t have implementation only when declared abstract.
  • Interface can inherit more than one interfaces
  • Abstract class can implement more than one interfaces, but can inherit only one class
  • Abstract class must override all abstract method and may override virtual methods
  • Interface can be used when the implementation is changing
  • Abstract class can be used to provide some default behavior for a base class.
  • Interface makes implementation interchangeable
  • Interface increase security by hiding the implementation
  • Abstract class can be used when implementing framework
  • Abstract classes are an excellent way to create planned inheritance hierarchies and also to use as non-leaf classes in class hierarchies.
A concrete example of an abstract class would be a class called Animal. You see many animals in real life, but there are only kinds of animals. That is, you never look at something purple and furry and say "that is an animal and there is no more specific way of defining it". Instead, you see a dog or a cat or a pig... all animals. The point is, that you can never see an animal walking around that isn't more specifically something else (duck, pig, etc.). The Animal is the abstract class and Duck/Pig/Cat are all classes that derive from that base class. Animals might provide a function called "Age" that adds 1 year of life to the animals. It might also provide an abstract method called "IsDead" that, when called, will tell you if the animal has died. Since IsDead is abstract, each animal must implement it. So, a Cat might decide it is dead after it reaches 14 years of age, but a Duck might decide it dies after 5 years of age. The abstract class Animal provides the Age function to all classes that derive from it, but each of those classes has to implement IsDead on their own.
What is Inheritance?
Inheritance is where one class (child class) inherits the members of another class (parent class).
The benefit of inheritance is that the child class doesn't have to redeclare and redefine all the members which it inherits from the parent class. It is therefore a way to re-use code. 
public class Exception
{
}

public class IOException : Exception
{
}

What is Polymorphism?
Polymorphisms is a generic term that means 'many shapes'. More precisely Polymorphisms means the ability to request that the same operations be performed by a wide range of different types of things.
At times, I used to think that understanding Object Oriented Programming concepts have made it difficult since they have grouped under four main concepts, while each concept is closely related with one another. Hence one has to be extremely careful to correctly understand each concept separately, while understanding the way each related with other concepts.
In OOP the polymorphisms is achieved by using many different techniques named method overloading, operator overloading, and method overriding

What is Method Overloading?
Method overloading is the ability to define several methods all with the same name.
public class MyLogger
{
    public void LogError(Exception e)
    {
        // Implementation goes here
    }

    public bool LogError(Exception e, string message)
    {
        // Implementation goes here
    }
}

What is Operator Overloading?
The operator overloading (less commonly known as ad-hoc polymorphisms) is a specific case of polymorphisms in which some or all of operators like +, - or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments.

public class Complex
{
    private int real;
    public int Real
    { get { return real; } }

    private int imaginary;
    public int Imaginary
    { get { return imaginary; } }

    public Complex(int real, int imaginary)
    {
        this.real = real;
        this.imaginary = imaginary;
    }

    public static Complex operator +(Complex c1, Complex c2)
    {
        return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
    }
}

I above example I have overloaded the plus operator for adding two complex numbers. There the two properties named Real and Imaginary has been declared exposing only the required “get” method, while the object’s constructor is demanding for mandatory real and imaginary values with the user defined constructor of the class.

What is Method Overriding?
When two or more methods (functions) have the exact same method name, return type, number of parameters, and types of parameters as the method in the parent class is called method overriding.
class parentClass
{
            public virtual void Disp(int i)
            {
                        System.Console.WriteLine("parentClass Display" + i);
            }
}
class childClass : parentClass
{
            public override void Disp(int i)
            {
                        System.Console.WriteLine("childClass Display" + i);
            }
}

Here you can see the method name, parameter and return type are same but one method is in the parent class and another one in the child class

Difference between method overloading and method overriding

Method overloading happens in the same class shares the same method name but each method should have different number of parameters or parameters having different types and order. But in method overriding derived class have the same method with same name and exactly the same number and type of parameters and same return type as a parent class.
Method Overloading happens at compile time while Overriding happens at runtime. In method overloading, method call to its definition has happens at compile time while in method overriding, method call to its definition happens at runtime. More about....

For more update you can follow me on my twitter handler : @mohitdagar80