Showing posts with label OOPS tutorial. Show all posts
Showing posts with label OOPS tutorial. Show all posts

07 June 2014

difference between compile time and run-time polymorphism

In this tutorial post let's understand what is polymorphism and what are the difference between compile time polymorphism and runtime polymorphism.

What is polymorphism

Polymorphism means exhibition in many forms. "Poly" means multiple and "morph" means forms. Combining the two words it becomes the exhibition of multiple forms.

polymorphism is having two types. One is called compile-time polymorphism and other is run time polymorphism.

First let's understand compile time polymorphism

class  Program
{
  static void Main(string[] args)
  {
   // passing 2 values to Add() method 
   // calls 2 parameters method
   long sum = Calculator.Add(1, 2);
   Console.WriteLine(sum);
   // Passing 3 values to Add() method 
   // calls 3 parameters method
   sum = Calculator.Add(1, 2, 3);
   Console.WriteLine(sum);
   Console.Read();
   }
}
public static class Calculator
{
public static long Add(int par1, int par2)
 {
   Console.WriteLine("Two parameter method called");
   long sum = par1+ par2;
   return sum;
 }
 public static long Add(int par1, int par2, int par3)
 {
  Console.WriteLine("Three parameter method called");
  long sum = par1 + par2 + par3;
  return sum;
  }
}

Output of the above function overloading program:

Two parameter Add() method called
3
Three parameter Add() method called
6

In the above Calculator class, we have two methods with the same name Add(). One of the methods is taking in two parameters; whereas the other method is taking in 3 parameters. Depending on how many parameters we are passing to a method, a different method is called. Here the name of the method is same, only the number of parameters is varying. This is called function overloading. So using function overloading we can achieve compile-time polymorphism.

Why its called compile time polymorphism?

Which methods get executed will be determined at the time of compilation only. Hence this is called compile time polymorphism. Because the method invocation is decided at compile time only, it cannot change at runtime based on the context. Hence compile-time polymorphism is also called static polymorphism.

Using Function overloading we can implement compile-time polymorphism.

Now let's understand the run time polymorphism

The best is to go through a code example.

class Program
{
 static void Main(string[] args)
 {
  //doctor variable refers to 
  //instance of base Doctor class
  Doctor doctor = new Doctor();
  doctor.TreatPatient();
  // doctor variable refers to 
  // instance of derived Surgeon class.
  doctor = new Surgeon();
  doctor.TreatPatient();
  Console.Read();
  }
}

public class Doctor
{
public virtual void TreatPatient()
 {
Console.WriteLine("Doctor class: I diagnose 
      patients and prescribe medicine."
);
 }
}

public class Surgeon : Doctor
{
 // Override the behavior of the base 
 // class and customize it.
 public override void TreatPatient()
 {
 Console.WriteLine("Surgeon class:
                   I do surgery."
);
 base.TreatPatient();
 }
}

Output of the above function overriding program:

Doctor class: I diagnose patients and prescribe medicine.
Surgeon class: I do surgery.
Doctor class: I diagnose patients and prescribe medicine.

In above program, Doctor is the base class and Surgeon is derived class. In Doctor class, the method TreatPatient() is defined as virtual. That means, the derived classes can override the behavior of the base class. In our example the derived class, Surgeon is specialized form of Doctor, who can do surgery and hence the TreatPatient() method is overridden.

For Doctor type variable, when the Doctor class instance [new Doctor()] is assigned and on invoking the TreatPatient() method, the Doctor class TreatPatinent() method gets executed.

Doctor class: I diagnose patients and prescribe medicine.

In the next line for the same doctor variable, instance of the derived class Surgeon [using new Surgeon()] is assigned and on invoking the TreatPatient() method, the Surgeon class TreatPatinet() method will get executed and displays the below output:

Surgeon class: I do surgery.
Doctor class: I diagnose patients and prescribe medicine.

Here depending on which type of the instance the doctor variable referring to, that respective type method gets invoked. So here the variable is same and method name called is same, but different implementation of the method will get executed. Its exhibiting different behavior depending on which instance of the class it refers to. So it's a polymorphism happening at runtime.

But why its called run-time polymorphism?

Which implementation of the TreatPatient() method should get executed is dynamic and decided at runtime depending on the instance the base class type variable is holding the reference to. And hence the name runtime polymorphism.

Using Function overriding we can implement run time polymorphism type.

Download Polymorphism demo project(project built on 3.5 .NET using VS 2008)

02 February 2013

What is abstraction in OOPS?

In many .NET and JAVA interview, one of the basic, yet important question being asked is, "What is abstraction" OR what you understand by Abstraction in OOPS?

Abstraction is one of the building blocks of Object Oriented Programming & Systems (OOPS). Let's go through the below topics to understand abstraction in OOPS.

  1. Abstraction English dictionary meaning
  2. Real world abstraction example
  3. Abstraction in OOPS definition
  4. Advantages of abstraction in OOPS

Abstraction English dictionary meaning:

  1. An idea not associated with any specific instance.
  2. The process of formulating general concepts by abstracting common properties of instances.

Real world abstraction example

Abstraction explained with real world example

By looking at the below picture what comes to your mind?

Possible guesses may be one of the below:
  1. Picture shows different kinds of cars.
  2. Picture shows different manufacture's car.

What made you think, "these are different kinds of cars?"

Your reasons may be one of the below:
  1. All the different images in the picture have 4 wheels.
  2. All have a steering wheel.
  3. All have an engine and a body.

If you look at the above points, it is clear all the above are characteristics of the car. Without any of the above features, it may not be possible to call an object as Car. If an object doesn't exhibit any of the above features, we will not call that object as a Car. That means if we want to call an object as Car, it has to have all the above features, without which it's not a car.

By now you are clear what is all about abstraction. Define a Car abstract class or an interface(Icar) in your programming language and all other different cars should provide an implementation for the ICar interface. Look out for common or general features of an object and define those features in an abstract class. Then all different types of the object have to provide the implementation for that abstract class, without which the object is not called an instance of the abstraction.

Abstraction in OOPS definition

Abstraction is a building block in OOPS. Allows loose coupling and defines common features for related objects so that they can be interchangeable.

Advantage of using abstraction

Using abstraction in OOPS design bring loose coupling in the system. When a system is loosely coupled with dependencies, you can easily plug & play the dependencies. Hence less of regression while switching to another dependency.

03 December 2012

Difference between compile time and run-time polymorphism

In many technical interviews for .NET developers role, the important question being asked is, what are two different kinds of polymorphism? OR what is the difference between compile time and runtime polymorphism?

Let's first understand what is all about polymorphism itself.

The WordWeb dictionary says "the existence of two or more forms". Applying this concept to OOPS, polymorphism is all about exhibiting different behavior depending on what it contains, either at the runtime or at the compile time. Sounds cryptic!, let's start with an example.

namespace Polymorphism
{
    http://rangahc.blogspot.in/2013/12/Csharp-class-tutorial.html Program
    {
        static void Main(string[] args)
        {
          // Passing 2 values to Add() method 
   // calls 2 parameters method
          long sum = Calculator.Add(1, 2);
           Console.WriteLine(sum);
         // Passing 3 values to Add() method 
         // calls 3 parameters method
           sum = Calculator.Add(1, 2, 3);
           Console.WriteLine(sum);
           // Wait till user enters any character on the console
           Console.Read();
        }
    }
    public static class Calculator
    {
        public static long Add(int operand1, int operand2)
        {
            Console.WriteLine("Two parameter Add() method called");
            long sum = operand1 + operand2;
            return sum;
        }
        public static long Add(int operand1, int operand2, int operand3)
        {
     Console.WriteLine("Three parameter Add() method called");
            long sum = operand1 + operand2 + operand3;
            return sum;
        }
    }

Output of the above function overloading program:

Two parameter Add() method called
3
Three parameter Add() method called
6

In the above Calculator class, we have two method with the same name Add(). One takes 2 parameters and another takes 3 parameters. Depending on how many parameters we are passing to the method, a different method is called. Here the name of the method is same, only the number of parameters is varying. This is called function overloading. So using function overloading we can achieve compile-time polymorphism.

But important interview question is, why it's called compile-time polymorphism.

Answer is that which method to call is decided at the compile time only not at the runtime and hence the name compile-time polymorphism. Compile time polymorphism is referred as static polymorphism.

Function overloading is of compile-time polymorphism type.

Now let's have a look at the runtime polymorphism.

The best is to go through an example. Let's create a one.

namespace RuntimePolymorphism
{
    class Program
    {
        static void Main(string[] args)
        {
            // doctor variable refers to 
   // instance of base Doctor class.
            Doctor doctor = new Doctor();
            doctor.TreatPatient();
            // doctor variable refers to 
   // instance of derived Surgeon class.
            doctor = new Surgeon();
            doctor.TreatPatient();
            Console.Read();
        }
    }
    public class Doctor
    {
        public virtual void TreatPatient()
        {
          Console.WriteLine("Doctor class: I diagnose 
                    patients and prescribe medicine.");
        }
    }
    public class Surgeon : Doctor
    {
       // Override the behavior of the base 
    // class and customize it.
        public override void TreatPatient()
        {
            Console.WriteLine("Surgeon class:
                              I do surgery.");
            base.TreatPatient();
        }
    }
}

Output of the above function overriding program:

Doctor class: I diagnose patients and prescribe medicine.
Surgeon class: I do surgery.
Doctor class: I diagnose patients and prescribe medicine.

As seen in the above program, Doctor base class and derived class Surgeon. In the Doctor base class, we have marked the method TreatPatient() as virtual. That means the derived classes can override the behavior of the base class. Derived class Surgeon is the specialized class of Doctor, who can do surgery. And hence TreatPatinet() method is overridden in the Surgeon class.

For the doctor variable when the Doctor class instance [new Doctor()] is assigned and on invoking the TreatPatient() method, the Doctor class TreatPatinent() method gets execute and displayed the below: Doctor class: I diagnose patients and prescribe medicine.

In the next line for the same doctor variable instance of the derived class Surgeon [using new Surgeon()] is assigned and on invoking the TreatPatient() method, the Surgeon class TreatPatinet() method gets execute and displayed the below:

Surgeon class: I do surgery.
Doctor class: I diagnose patients and prescribe medicine.

Here depending on what which class instance doctor variable reference, that class method gets executed. So here the variable is same and a method called is same, but different implementation of the method gets to execute. Its exhibiting different behavior depending on which instance of the class it refers to. So its a polymorphism.

But why its called run-time polymorphism?

Answer is simple. Which implementation of the TreatPatient() method should get executed, is not decided at the compile time and its decided at runtime depending which instance of the class is assigned. And hence the name runtime polymorphism.

Function overriding is of runtime polymorphism type.

Download sample demo project in C# .NET(project built on 3.5 .NET using VS 2008)

You may interested in below OOPS related topics:

You may also interested in below recent C# tutorials: