yeasir007

Monday, November 26, 2012

Introducing Object Oriented Programming(OOP) Concept


OOP Basic concept on    Object,Class,Method,Encapsulation,Inheritance,Polymorphism,Interface,Abstract Class etc:

What is OOP(Object Oriedted Programming)?
Object-oriented programming (OOP) is a programming language model organized around "objects" rather than "actions" and data rather than logic. Historically, a program has been viewed as a logical procedure that takes input data, processes it, and produces output data. The programming challenge was seen as how to write the logic, not how to define the data. Object-oriented programming takes the view that what we really care about are the objects we want to manipulate rather than the logic required to manipulate them.
Object oriented programming uses objects to design applications. This technique is designed to isolate data. The data and the functions that operate on the data are combined into single unit. This unit is called an object. Each object can have properties and member functions. You can call member function to access data of an object. It is based on several techniques like encapsulation, modularity, polymorphism, and inheritance. 
Basic elements of OOP are:
ü  Object
ü  Class
ü  Method
ü  Encapsulation
ü  Information Hiding
ü  Inheritance
ü  Polymorphism
We will describe it step by step.


Object Oriented Programming Philosophy :
Before starting Object Oriented Programming (OOP) we should know, what an object is and how to think in Object Oriented way. Yes, Starting of Object Oriented Programming is of course the concept of object. And this concept is really simple. Ok, I am starting to speak about it. Before starting, I am requesting you to forget everything about programming, database design, software design i.e. all kinds of software engineering and programming language details for some couple of minutes (not forever!!).


Everything can be an object:
Look around you, what we see, ALL ARE OBJECTS. We see computer, chair, table, pen, air cooler, carpet etc., all these are objects. Why they are object? Pretty simple, they have some related attributes and some related activities. How? Ok, just think about computer, it has processor, RAM, hard drive, keyboard, mouse, etc. All these are the attributes of computer. Now, what’re the activities of a computer? It has a lot: it runs antivirus program, displays information, accepts requests and executes these properly. All these are the activities of computer. So, computer is an object. In the same way, we will get the attributes and activities of chair, table, etc. So, to be an object, something should have attributes and/or should have activities. Finally, from the above discussion, we can draw a conclusion:

How it is possible? Is it possible that any event, like war or raining, singing, thinking etc. (which is not visible) can be object? The answer is YES. These can be objects also. Think, raining has attributes: is it drizzling or “cats and dogs”? Singing can be an object if we consider, in which frequency-range it is sung? ‘Name’ – is it an attribute or an object? Actually, it is totally depend on problem domain. See, if you are thinking about a banking solution then customer ‘Name’ will be an attribute of customer. But if it a business from where you can purchase the ‘Name’ of your new-born baby then ‘Name’ will be an object to this business. Because ‘Name’ has meaning, length, type etc. 




Object’s data and responsibility depend on problem domain:
If I tell you and your friend to find out the data and activity of customer object, suppose, you get customer with name, email, phone attributes and purchase, bargain activities. At the same time your friend may get customer with first name, middle name, last name, gender, credit card attributes and open account activity.

Why it happens? It happens because you and your friend were on different platform with different point of view. You think about the customer of a grocery store whereas your friend thinks about the customer of a bank. But both of you are right.So, object and its data, responsibility everything totally depends on problem domain.


What is class?
A class represents description of objects that share same attributes and actions. It defines the characteristics of the objects such as attributes and actions or behaviors. It is the blue print that describes objects.
Suppose, I say Nashra, Maksura and Misha are students. Here, Nashra, Maksura and Misha are objects and Student is the class. More specifically, Student is the class with name attributes and there are three student objects whose names are Nashra, Maksura and Misha.
Mapping Object Oriented Thoughts to Object Oriented Programming:
To make our conception more clear, now we will try to make a small application. Of course, we will try it Object Oriented way. Let’s start. Suppose our considering problem domain as follows: “………User wants to get full name and reverse full name providing first name, middle name and last name of a person.”

We will identify the objects first. Here, we will get ‘Person’ object as follows:
Person
     ü  Has first name
     ü  Has middle name
     ü  Has last name           
     ü  Can tell its full name
     ü  Can tell its reverse name

Now we will implement this in C# (VS 2008, DotNet 3.5), an OOP language.
Steps:
1.     Start Microsoft Visual Studio 2008
2.     Click File>New>Project

We will see the following window. Select ‘Class Library’ template, give a meaningful name and select your preferable location.

    3.    Click ‘Ok’ Button
4.    In Solution Explorer, we will see Class1.cs file. Delete this file.
5.    Select project (not solution) OOPWalkThrough1 and Click right button. Then Click on Add>Class from the popup menu. We will get following window.

6.     Remind we have found an object, ‘Person’ in our problem domain. Here we will give ‘Person.cs’ in Name as a file name.
7.     Click ‘Add’ button and we will see the following code:
         using System;
      namespace OOPWalkThrough1
      {
       class Person
       {
        //.............
       }
      }

   Here, Person is a class.
  8. Now update the Person class as follows:
        namespace OOPWalkThrough1
    {
       class Person
       {
        public string firstName;
        public string middleName;
        public string lastName;

        public string GetMyFullName()
        {
           return firstName + " " + middleName + " " + lastName;
        }

        public string GetMyReverseName()
        {
           string reverseName = "";
           string fullName = GetMyFullName();
           for (int index = fullName.Length - 1; index >= 0; index--)
           {
              reverseName += fullName[index];
           }
           return reverseName;
        }
     }
    }

Have a look inside the Person class. Compare the identified object (Person) with the Person class.
We see data of Person are represented by attributes and responsibilities are represented by methods. So any object creates from Person class will represent our domain object, Person. 

Now add another class in this project. Here file name will be EntryPoint.cs (or any meaningful name you like) and write Main () method inside this class as follows:

Here, we will create a Person object, personObj from Person class using the following line:
                        Person personObj = new Person();
Then assign some data to the attributes of personObj as follows:


  personObj.firstName = "Nashra";
  personObj.middleName = "Misha";
  personObj.lastName = "Maksura";

Finally, ask personObj to tell it’s full name and reversed-name and get it:

  string fullName = personObj.GetMyFullName();
  string reverseName = personObj.GetMyReverseName();

10. To make the project executable, we need to change the project properties. Select the project, click right button, select Properties from pop-up menu; we will get the following tab to change project properties.


Select Output Type as Console Application and Startup object as OOPWalkThrough1.EntryPoint.

11.Run the application and we will the output:
12.To take input from user we need to change the Main() method. Replace these three lines:
               personObj.firstName = "Nashra";
          personObj.middleName = "Misha";
          personObj.lastName = "Maksura";
with the following three lines
               personObj.firstName = Console.ReadLine();
          personObj.middleName = Console.ReadLine();
          personObj.lastName = Console.ReadLine();

Important Note: Here, to keep the example simple, I’ve violated encapsulation (keep the data public) principle. To solve a problem, mapping a domain object directly to software object sometimes may not be a good solution.



Separate Business Logics from user interface:

Separate Business Logics from user interface of DirtyCalculator application:
In your C# basic classes, you may write calculator like this given DirtyCalculator (See the DirtyCalculator Example). In this example, everything has been written inside CalculatorUI class as follows:
    public partial class CalculatorUI : Form
    {
    public CalculatorUI()
    {
        InitializeComponent();
    }
    private void addButton_Click(object sender, EventArgs e)
    {
        double firstNumber = Convert.ToDouble(firstNumberTextBox.Text);
        double secondNumber = Convert.ToDouble(secondNumberTextBox.Text);
        double result = (firstNumber + secondNumber);
        resultTextBox.Text = result.ToString();
    }
    private void subtractButton_Click(object sender, EventArgs e)
    {
        double firstNumber = Convert.ToDouble(firstNumberTextBox.Text);
        double secondNumber = Convert.ToDouble(secondNumberTextBox.Text);
        double result = (firstNumber - secondNumber);
        resultTextBox.Text = result.ToString();
    }
    private void multiplyButton_Click(object sender, EventArgs e)
    {
        double firstNumber = Convert.ToDouble(firstNumberTextBox.Text);
        double secondNumber = Convert.ToDouble(secondNumberTextBox.Text);
        double result = (firstNumber * secondNumber);
        resultTextBox.Text = result.ToString();
    }
    private void divideButton_Click(object sender, EventArgs e)
    {
        double firstNumber = Convert.ToDouble(firstNumberTextBox.Text);
        double secondNumber = Convert.ToDouble(secondNumberTextBox.Text);
        double result = (firstNumber / secondNumber);         
        resultTextBox.Text = result.ToString();
    }
   }
So, if I want to change this calculator to web application or even to console application, I will delete CalculatorUI.cs class and then all the arithmetic logic (addition, subtraction, multiplication and deletion) will be deleted from my code and I have to write these logics from starting. Think this situation for an enterprise application!! If user wants to change User Interface everything will be started from the beginning.

Another problem with this DirtyCalculation is: if I want to use this calculator (these four arithmetic operations) in another part of this program. I have re-write these logics there. So, I want to change any logic it will be very difficult to manage because same logics have been re-written in several places.   
  
So, actually, what’s wrong I have done in DirtyCalculator? Why do I need to rewrite my logic if my application is changed?

Yes, I mixed everything inside CalculatorUI. Any UI is responsible for displaying and taking information from the user but here I implemented everying inside UI code. Now as we can think in OO way we should refactor* (Make your code more clean without changing the features) this DirtyCalculator to separate the logic from UI. Don’t start with big changes, If start with massive changes at a time, you can’t manage it. Take ‘Baby steps’, do little changes.

With the four arithmetic logics we can think a separate a new object. So, we can write add a new class in our application which name can be Calculator. See the following code for our Calculator class.
    public class Calculator
    {
     public double Add(double firstNumber, double secondNumber)
     {
        return (firstNumber + secondNumber);
     }

     public double Subtract(double firstNumber, double secondNumber)
     {
        return (firstNumber - secondNumber);
     }

     public double Multiply(double firstNumber, double secondNumber)
     {
        return (firstNumber * secondNumber);
     }

     public double Divide(double firstNumber, double secondNumber)
     {
        return (firstNumber / secondNumber);
     }
    }

Finally update our CalculatorUI class as follows:
   public partial class CalculatorUI : Form
   {
    public CalculatorUI()
    {
        InitializeComponent();
    }

    double firstNumber = 0;
    double secondNumber = 0;
    double result = 0;
    Calculator calculatorObj = new Calculator();

    private void addButton_Click(object sender, EventArgs e)
    {
        firstNumber = Convert.ToDouble(firstNumberTextBox.Text);
        secondNumber = Convert.ToDouble(secondNumberTextBox.Text);
        result = calculatorObj.Add(firstNumber, secondNumber);
        resultTextBox.Text = result.ToString();
    }

    private void subtractButton_Click(object sender, EventArgs e)
    {
        firstNumber = Convert.ToDouble(firstNumberTextBox.Text);
        secondNumber = Convert.ToDouble(secondNumberTextBox.Text);
        result = calculatorObj.Subtract(firstNumber, secondNumber);
        resultTextBox.Text = result.ToString();
    }

    private void multiplyButton_Click(object sender, EventArgs e)
    {
        firstNumber = Convert.ToDouble(firstNumberTextBox.Text);
        secondNumber = Convert.ToDouble(secondNumberTextBox.Text);
        result = calculatorObj.Multiply(firstNumber, secondNumber);
        resultTextBox.Text = result.ToString();
    }

    private void divideButton_Click(object sender, EventArgs e)
    {
        firstNumber = Convert.ToDouble(firstNumberTextBox.Text);
        secondNumber = Convert.ToDouble(secondNumberTextBox.Text);
        result = calculatorObj.Divide(firstNumber, secondNumber);         
        resultTextBox.Text = result.ToString();
    }
  }

In CalculatorUI class, we create a Calculator object, calculatorObj and call its related method in related button click code (See the final code in StartCalculator example). Now, we don’t have such kind of problems we’ve faced in our DirtyCalculator. If we change this Windows Form Application to Web Application or even to Console Application, we just delete the CalculatorUI only and our Calculator class with intact. Also, if we want use any arithmetic operation in any other class in this program, we can just create an object of Calculator class and call the desired methods. We don’t need to repeat the logic.

Data Hiding ,Constructor & Property :

Data Hiding: Data hiding concept restricts direct exposure of data. Data is accessed indirectly using safe mechanism, methods in case of programming object. Taking bike as an example, we have no access to the piston directly, we can use 'start button' to run the piston. You can understand the advantage of information hiding concept from this example. If a bike manufacturer allows direct access to piston, it would be very difficult to control actions on the piston. 

In object oriented programming, we must hide the internal data of an object. But in our previous example we keep firstName, middleName and lastName public of Person class:
class Person
 {
   public string firstName;
   public string middleName;
   public string lastName;
   --------
   --------
 }

This is a violation of encapsulation. So, we must update Person class, making all data private.
 class Person
 {     
  private string firstName;
  private string middleName;
  private string lastName;
  --------
  --------
 }

Then how can we access these personObj data from UI() ? Putting full-stop after personObj, we will not get access of firstName, middleName and lastName. How can we solve this?

We can write methods to get the access of these private data as follows: Here, we write it only for firstName attribute only.
class Person
 {
   private string firstName;
   private string middleName;
   private string lastName;
   --------
   --------
}
public void SetFirstName(string firstName)
{
 this.firstName = firstName;
}
public string GetFirstName()
{
 return firstName;
}


Now, we can set a value of firstName by SetFirstName(string firstName) method.
     personObject.GetFirstName("Nashra");

And to get data from personObj we may write:
     string firstName = personObject.GetFirstName;

Constructor: It’s used to initialize an object when it is created. Or even to do some initial activity.
public Person(string firstName, string middleName, string lastName)
 {
  this.firstName = firstName;
  this.middleName = middleName;
  this.lastName = lastName;
 }

See, when we create object from Person class we have to provide these three data as follows:
   Person personObject = new Person("Nashra","Misha","Maksura");

PropertyIn Data Hiding topics, we see, for three attributes of person class you need to wirte six methods which really shows Person class little bit awkarding. We should not write methods for this purpose. Another cause is “Method represents the responsibility, so for accessing data we shouldn’t write methods.” Better we can try property (in .NET only). So, remove methods from our code and write property.
 class Person
 {
  private string firstName;
  private string middleName;
  private string lastName;

  public string FirstName
  {
   get { return firstName; }
   set { firstName = value; }
  }
  public string MiddleName
  {
   get { return middleName; }
   set { middleName = value; }
  }
  public string LastName
  {
   get { return lastName; }
   set { lastName = value; }
  }
 }

To access data using property from UI() method is as follows:
personObject.FirstName = "Nashra";
personObject.MiddleName = "Misha";
personObject.LastName = "Maksura";

If we don’t need to share our data with our client code, we don’t need to write property for this data i.e. data should be private. If we want to keep the data read only, write the property with get part only, don’t write set part. We can write property for getting access of combinational data only. We can write MyFullName property instead of GetMyFullName () method of Person class.
public string MyFullName
{
  get
    {
      return firstName + " " + middleName + " " + lastName;
    }
}

Generally, these kinds of properties have only get part.


Method Overloading: Overloading allows multiple functions to exist with same name but different parameters. Again if you take bike as an example, it has a function ‘Start’ with two forms i.e. 'Auto Start' and 'kick start'.

In our calculator example, now I want to write a method by which we can add three numbers. How can we do it? We can write a method “AddThreeNumber” which will takes three numbers as parameter and returns the add result. So, we have two add methods:
ü  Add’ for adding two numbers.
ü  AddThreeNumber’ for adding three numbers.

Better we rename Add’ method to AddTwoNumber.

Good. But think about our client who will use our code. After creating object of Calculator class, (s) he will get total five methods for arithmetic operation:

AddTwoNumber’ and AddThreeNumber’ really do similar job, first one adds two numbers and  second one adds three numbers. Ultimately both methods do the same job: Adding.

So, if we write distinct methods for these kinds of similar jobs, client of my code will see lots of methods (activities) and this makes him more confuse about the object’s responsibilities.

Better use method overloading concept here. Write Add method with two parameters and with three parameters.

public double Add(double firstNumber, double secondNumber)
public double Add(double firstNumber, double secondNumber, double thirdNumber)

Now the client of our code is really happy, (s)he only sees Add method in his code. Get Add method with two parameters and three parameters.

Finally, we can say similar responsibilities should be written using method overloading concept.

Constructor Overloading: We use constructor to initialize an object. If we want to initialize an object in several ways, we need constructor overloading.

If user of Person class wants in initialize in several ways we need to update our Person class:

public Person()
{

}
public Person(string firstName, string lastName)
{
    this.firstName = firstName;
    this.LastName = lastName;
}
public Person(string firstName, string middleName, string lastName)
{
    this.firstName = firstName;
    this.middleName = middleName;
    this.lastName = lastName;
}

We can reuse Person (string firstName, string lastName) in our third constructor:

     public Person()
    {

    }
    public Person(string firstName, string lastName)
    {
        this.firstName = firstName;
        this.LastName = lastName;
    }
    public Person(string firstName, string middleName, string lastName) : this (firstName, lastName)
    {
        this.middleName = middleName;
    }




Static Member, Namespace & Access Modifier:

Static members of a class:
It is one kind of data or activities belongs to a class not an object of that class.
From our object oriented concept we know that object has data (attributes) and has responsibilities. Data is represented by variables and responsibilities are represented by methods.

But in problem domain sometimes you will get some data and responsibilities which NOT belong to object (not with a specific instance of the class), these belong to class. These types of members are the static members.

All of you are familiar with the object or instance of Trainee class. To create trainee object we write Trainee class as follows (For simplicity in discussion, I keep all data public):
class Trainee
 {
   public string name;
   public string id;
   public string email;
 }

So, we create an object from this class:
Trainee traineeOne = new Trainee()
 traineeOne.name = "SweetPaglee";

So, actually name, id, email are the data of each object of Trainee type class. But just consider ‘No of Trainees’ as an attribute of trainee object. Is it meaningful? No, it is not. This kind of attributes is static which actually belongs to the class, not the object.
class Trainee
 {
   public string name;
   public string id;
   public string email;

   public static int numberOfTrainees;
 }

This attribute, NumberOfTrainees doesn’t depend on any object data. Static members belong to the class, rather than an instance, they are accessed through the class, not through any objects of that class.”
Trainee.numberOfTrainees = 30;
int noOfTrainee = Trainee.NumberOfTrainee;

Similarly, Think about your Calculator class. Do you really need to create object for calculator class. Calculator class is an utility class and is has no data of it’s own.
So, you can make all of it’s methods are static.

namespace DirtyCalculator
 {
 public class Calculator
 {
    public static double Add(double firstNumber, double secondNumber)
    {
        return (firstNumber + secondNumber);
    }

    public static double Subtract(double firstNumber, double secondNumber)
    {
        return (firstNumber - secondNumber);
    }

    public static double Multiply(double firstNumber, double secondNumber)
    {
        return (firstNumber * secondNumber);
    }

    public static double Divide(double firstNumber, double secondNumber)
    {
        return (firstNumber/secondNumber);
    }
  }
 }

Now, in UI code you just call it in the following way:
double result = Calculator.Subtract(firstNumber, secondNumber);

If you use static keyword before class name, it means that all the members of this class must be static and you can’t write any non-static method/property/attribute of this kind of class.

Static Constructor:
Instance or object constructors are used for initializing an object. If we want initialize a class we have to write static constructor. To create a static constructor for Trainee class, we can write:

    class Trainee
     {
     static Trainee()
     {
        numberOfTrainees = 30;
     }

     public string name;
     public string id;
     public string email;

     public static int numberOfTrainees;
     }

Here, we initialize a static data, numberOfTrainees using static constructor.

Question: Is it possible to use non-static members from static members?
We cannot call a static constructor directly. It is executed only for one time before the first instance of the class is created or even before any static methods are used. You can’t use any access modifier before static constructor and it have no overload

Organize your class using namespace:
Namespaces are the logical separation of our classes. Namespaces function as both an internal system to organize our application as well as an external way to avoid name clashes (collisions) between our codes or even with other applications.

We will keep related classes in a particular namespace so that we can easily get our desired classes. .Net Framework has lots of classes so they have several namespaces where they keep related classes.

.Net Framework namespace:
Namespace
Definition
System.Windows.Forms
Provides the classes that are useful for building applications based on Microsoft Windows®
System.IO
Provides classes for reading and writing data to files
System.Data
Provides classes that are useful for data access
System.Web
Provides classes that are useful for building Web Forms applications
The root namespace of .Net Framework is System.


‘using’ directive:
To use a particular class in your code, you have to tell it’s namespace with ‘using’ directive.Suppose we want to use Form, Button and TextBox class in our code, we have to write using System.Windows.Forms above of our class because these controls located in this namespace.

Access Modifiers:
By using access modifiers, you can define the scope of class members in your applications. It is important to understand how access modifiers work because they affect your ability to use a class and its members.

There are five access modifiers in C# code.
     ü   Private
     ü  Public
     ü  Internal
     ü  Protected
     ü  protected-internal

Declaration
Definition
public
Access is not limited: any other class can access a public member.
private
Access is limited to the containing type: only the class containing the member can access the member.
internal
Access is limited to this assembly: classes within the same assembly can access the member.
protected
Access is limited to the containing class and to types derived from the containing class.
protected internal
Access is limited to the containing class, derived classes, or to classes within the same assembly as the containing class.


Inheritance :

Inheritance Relationship:
Inheritance concept in OOP allows us to create a new class using an existing one. It also allows the new class to add its own functionality. This concept can also be related to real world entity. A bike manufacturer uses same mechanism of existing version of the bike while launching a new version with some added functionalities. This allows him to save time and efforts.

In bank problem domain you will get Branch, Customer, Loan etc. as a domain objects and all are distinct objects. Also you will get another objects Savings Account, Checking Account which are not distinct they are similar in some points.

They are similar because they have something common facilities with each other. Both of them are account number, customer, withdraw and deposit. But distinctly Savings account has interest amount whereas and Checking account sometimes customer needs to pay to bank for services. Oppositely, checking account has service charge and keeps number of transactions.

Using class diagram we can represent the above discussion as follows:

This kind of relationship can be presented using IS-A relationship and we can implement inheritance feature here. The following picture depicts our above discussion.

  
Figure: Here, Savings and Checking account has some data and behaviors (account number, balance, withdraw and deposit) which has been owned by Account number so both accounts inherit these from account class.

Now we will start our code. First of all we write the Account class as follows:
  public class Account
  {
    private string accountNumber;
    private double balance;
 
    public bool Deposit(double amount)
    {
        balance += amount;
        return true;
    }
 
    public bool Withdraw(double amount)
    {
        balance -= amount;
        return true;
    }
  }

Pretty simple class. It has two data and two functionalities.

Now, we will implement the Savings Account class:
public class SavingsAccount : Account
{
    private double interestAmount;
 
    public double InterestAmount
    {
        get { return interestAmount; }
        set { interestAmount = value;}
    }
}


Here, you see we use the Account class as the base class of SavingsAccount. So, basically SavingsAccount has interestAmount with all the public and protected data and functionalities that Account has. As accountNumber and balance are private in Account class so SavingsAccount doesn’t get access of these. So, we will write the public property for these two types of data (accountNumber & balance) in Account class:

 public string AccountNumber
 {
   set { accountNumber = value; }
   get { return accountNumber; }
 }
 public double Balance
 {
   get { return balance; }
 }

Keep the balance read-only (without set), as it is changed by transaction. Ok, in the same way we will implement the Checking account and it will be:
public class CheckingAccount : Account
{
    private int numberOfTransactions = 0;
    private double serviceCharge;
}

HereSavingsAccount and CheckingAccount own the common part from Account by using it as their base class.

Note: You cann’t inherits data and/or behaviors from multiple class in C# i.e. in C# multiple inheritance is not possible.

We have a problem with numberOfTransactions of CheckingAccount as it should be changed in every withdraw and deposit. But we solve it later. So far, we have implemented inheritance relationship between classes as our picture.
Practice 1:


Here, after running this application user will enter data for savings and checking account and press Create button for each type of account. User will only create one savings and one checking account and (s) he will do it initially.

After creation, both account numbers will be enlisted in Select Account combobox. User will select any account number from the list and can withdraw and deposit using Transaction panel. User clicks Display button to see (See figure) the account number, balance and interest amount for Savings account. For Checking (s) he will only see account number and balance. (In this practice, skip the number of transactions for Checking Account).












Figure: Displaying accounts’ information

Encapsulation:

Encapsulation concept in OOP:
Encapsulation means keeping actions and attributes together under a single unit. This can also be understood using a motor bike example. A bike has actions such as 'switch on light', 'horn' etc. and attributes such specific color, size, weight etc. Here the actions and attributes are bundled together under a single unit, bike. In a programming language, methods and properties that correspond to actions and attributes respectively are kept under a unit called object. The advantage of encapsulation is that the implementation is not accessible to the client. The user has to know only the functionality of encapsulated unit and information to be supplied to get the result.

Polymorphism:

Polymorphism in OOP:
Polymorphism means the ability to take more than one form. An operation may exhibit different behaviors in different instances. It means same operation may behave differently on different classes. The behavior depends on the data types used in the operation. In programming language Method Overloading & Method Overriding express the term of polymorphism. Method Overriding is also known as dynamic polymorphism


Method Overriding:
In our previous discussion we have learned how to establish inheritance relationship between classes. Base class holds common things and sub classes inherit these. The advantage of inheritance is common implementation which increases the reusability.

Now what is Method Overriding? If any sub class has specific behavior over a common behavior of base class. Then sub class can override the specific method/property of base class. The following discussion will help you more to understand it:  

To start the implementation of Method Overriding, we are changing our above specification for withdraw activity.

For ‘withdraw’, Savings and Checking account has their own roles. For Savings minimum balance is 1000 and it is 0 (zero) for Checking. So, before withdraw you have to check it. But you see the withdraw method is implemented in Account, the base class.
So, how can we proceed?
Ok, see the following code for Savings account:
public bool WithdrawInSavingsAccount(double amount)
{
 if (Balance - amount >= 1000)
 {
    //Use base class Withdraw method if condition is fulfilled
    return Withdraw(amount); 
 }
 else
 {
    return false;
 }
}


Yes, it is one of the solutions. But in this situation we can use method overriding. We override Account’s Withdraw method in Savings Account. To do it at first, you need to change a little in Withdraw method of Accounts class.

Add virtual keyword in Withdraw method signature in Account class:

public virtual bool Withdraw(double amount)

Update the Savings account as follows:

public override bool Withdraw(double amount)
{
 if (Balance - amount >= 1000)
  {
    //Use base class Withdraw method if condition is fulfilled
    return Withdraw(amount);
  }
 else
  {
    return false;
  }
}

Yes, here, we override the Withdraw method of Account class in Savings Account class. Savings Account inherits the common logic for Withdraw from Account class and overrides it to implement it’s own logic inside it.

Note: To override a method in sub class, you have to keep the method signature same as it is in base class.

Using base constructor:

We can write constructor for both Savings and Checking accounts. Client code will pass Account no, interest rate for Savings and Account no, Service charge when creating them.

The following code is for Savings Account:

public SavingsAccount(string accountNo, double interestRate)
{
 AccountNo = accountNo;
 this.interestRate = interestRate;
}

For initializing Account number, we use base class property, AccountNo in the Savings account constructor. Still we have a better way to do it:

At first, write a constructor in Account base class:

public Account(string accountNo)
{
 this.accountNo = accountNo;
}

Now delete the previous constructor code for Savings Account and write a new one as follows:

public SavingsAccount(string accountNo, double interestRate): base(accountNo)
{
this.interestRate = interestRate;
}

SavingsAccount constructor initialize only it’s own interest rate and use base construcor for initializing Account number.

Please, in same way write the constructor for Checking Account.

If you want to keep parameterless constructor for both Savings and CheckingAccount you can write:

public SavingsAccount()
 {  
  //....
 }
public CheckingAccount()
 {  
     //.......
 }

You will face a complie error. Basically these two errors occur as they call parameterless (but you don’t see it) constructor of their base class. As you have written a constructor for base class, the default parameterless constructor has been destroyed. So, to compile your code you have to write down a parameneterless constructor in base class.
 
public Account()
 {
 
 }


Up-Casting and Down-Casting:
In our banking example, Account is the base class and Savings, Checking is the sub classes. So it is possible to keep a sub class’s object to the base class reference. So, you can write:
Account mySavingsAccount = new SavingsAccount();

Here, mySavingsAccount is a reference of Account base class where we keep a SavingsAccount type object.This is called Up-Casting.

Now, what the question is:
What will be accessible from mySavingsAccount?Will we get access of InterestRate of Savings account in mySavingsAccount?

The answer is No. You only get the access of common data and behavors between Account (base) and Savings (sub).

Now think about ‘Withdraw’ method.
Which ‘Withdraw’ method will be called? ‘Withdraw’ of Savings (sub) or ‘Withdraw’ of Account (base)?

The answer is: ‘Withdraw’ of Savings (sub) will be called.

Interface & Abstract Class:

What is Interface :
An Interface is a group of constants and method declaration. .Net supports multiple inheritances through Interface. Its states “what” to do, rather than “how” to do. An interface defines only the members that will be made available by an implementing object. The definition of the interface states nothing about the implementation of the members, only the parameters they take and the types of values they will return. Implementation of an interface is left entirely to the implementing class. It is possible, therefore, for different objects to provide dramatically different implementations of the same members.
For example, the Car object might implement the IDrivable interface (by convention, interfaces usually begin with I), which specifies the GoForward, GoBackward, and Halt methods. Other classes, such as Truck, Aircraft, Train or Boat might implement this interface and thus are able to interact with the Driver object. The Driver object is unaware of which interface implementation it is interacting with; it is only aware of the interface itself.
public interface IDrivable
 {
  void GoForward(int Speed);
 }
 public class Truck : IDrivable
 {
   public void GoForward(int Speed)
   {
     // Implementation omitted
   }
 }
 public class Aircraft : IDrivable
 {
  public void GoForward(int Speed)
  {
   // Implementation omitted
  }
 }
 public class Train : IDrivable
 {
  public void GoForward(int Speed)
  {
   // Implementation omitted
  }
 }

Keep in mind due to implement Interface.
ü  Each variable declared in interface must be assigned a constant value.
ü  Every interface variable is implicitly public, static and final.
ü  Every interface method is implicitly public and abstract.
ü  Interfaces are allowed to extend other interfaces, but sub interface cannot define the methods declared in the super interface, as sub interface is still interface and not class.
ü  If a class that implements an interface does not implements all the methods of the interface, then the class becomes an abstract class and cannot be instantiated.
ü  Both classes and structures can implement interfaces, including multiple interfaces.


What is abstract class?
A class which only specifies properties, not used to create objects and only used as a base class/supper class is called Abstract class. Derived class must define the properties of Abstract class. Generally, abstract class is a class where one or more methods/property is in abstract form. But it is also possible that an abstract class have no any abstract member (method/property).It’s also work as design guidelines. By using abstract key word in base class we ensure the face that derived class must “redefine” the properties to fulfill the desired functionality. Thus the from the abstract class point of view, the properties are only specified but not fully defined. The definition including the semantics of the properties must be provided by derived class.
Example of abstract:
public abstract class Account
{
    private double balance;
    private string accountNo;
 
    public Account()
    {
        balance = 0;
    }
 
    public Account(string accountNo)
    {
        this.accountNo = accountNo;
    }
 
    public double Balance
    {
        get { return balance; }
    }
 
    public string AccountNo
    {
        get { return accountNo; }
    }
 
    public virtual bool Deposit(double amount)
    {
        balance = Balance + amount;
        return true;
    }
 
    public virtual bool Withdraw(double amount)
    {
        balance = balance - amount;
        return true;
    }
}

Here, the class is abstract but there is no method or property in abstract form.

Another example of abstract class:
  public abstract class Account
  {
    private double balance;
    private string accountNo;
 
    public Account()
    {
        balance = 0;
    }
    public abstract double GetYearlyDeductionAmount();
    public Account(string accountNo)
    {
        this.accountNo = accountNo;
    }
    public double Balance
    {
        get { return balance; }
    }
    …………………………………
    …………………………………
   }

In this example, you see, there is an abstract method, GetYearlyDeductionAmount() inside abstract class, Account.

Generally, an abstract class is used as a base class of other classes. In the first example, only class is abstract and all other things are non-abstract. In our inheritance example we use Account (non-abstract) class as the base class of Savings and Checking account. So, what’s the difference if we use the first example’s abstract Account class as a base class of Savings and Checking account? Actually, there’s no difference in base-sub class relationship, if only class is abstract. There’s difference from another point of view. You can’t create object of Account class from any client code, as it is abstract class.
 Account accountObj = new Account();

If you write this code, you will get a compile error. It’s not possible to create object of any abstract class.

If Savings Account inherits this abstract Account class, still you can write this:
   Account accountObj = new SavingsAccount();

Here, you create a reference, accountObj of Account class and keep a Savings Account’s object in this reference.

Now, the question about second example. If we use the second example’s Account class (abstract and has an abstract method also) as a base class of Savings or Checking account, what will happen? The answer is:

Savings and Checking account have to implement abstract method GetYearlyDeductionAmount() with their own specific logic.

We get some design guideline also. Suppose, a new type of account (Loan account) we need to create in our application? What will we do? If we see Loan account has same data and functionality (may have some additional also) of Account class. It will use Account class as a base class and get access of common implementation and data of base, Account class.



Difference between Interface and Abstract Class:

                Interface
                 Abstract class
Multiple inheritance
A class may implement several interfaces.
A class may extend only one abstract class.
Default implementation
An interface cannot provide any code at all, much less default code.
An abstract class can provide complete code, default code, and/or just stubs that have to be overridden.
Constants
Static final constants only, can use them without qualification in classes that implement the interface. On the other paw, these unqualified names pollute the namespace. You can use them and it is not obvious where they are coming from since the qualification is optional.
Both instance and static constants are possible. Both static and instance initialize code are also possible to compute the constants.
Homogeneity
If the entire various implementations share is the method signatures, then an interface works best.
If the various implementations are all of a kind and share a common status and behavior, usually an abstract class works best.
Maintenance
If your client code talks only in terms of an interface, you can easily change the concrete implementation behind it, using a factory method.
Just like an interface, if your client code talks only in terms of an abstract class, you can easily change the concrete implementation behind it, using a factory method.
   Adding    functionality
If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method.
If you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change.

























In which Scenario you will go for Interface or Abstract Class?Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. Even though class inheritance allows your classes to inherit implementation from a base class, it also forces you to make most of your design decisions when the class is first published.

Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.




Thank you for staying with me. Best of luck.



No comments:

Post a Comment

Thanks for your comments