What is an Interface and how is it different from Abstract Classs?

An interface in C# is a type just like class is a type.  The difference between interface and class is that an interface only contains the method headers (no implementation of methods and no attributes) where as a class contains both attributes, methods and method implementations.

public interface IBankAcccount
    double AccountBalance();
    bool  IsActive();

Note that we havent declared if a method is public or  private.  In an interface all the methods are public and abstract. So, we need not specify the accessibility type in an interface.

Implementing an Interface (not inheriting an interface)Example
public Class SavingsAccount : IBankAcccount
   public double AccountBalance()
       Console.WriteLine (“The business logic for the account balance goes here “);
    bool  IsActive()
           Console.WriteLine (“The business logic for the ISACTIVE goes here “);

Abstract Class Vs Interfaces

Abstract Class Interface
Abstract Class specifies the data structure and a mixture of concrete and abstract methods. Note that an Abstract class can contain only abstract methods. In such situations we use Interface. Interfaces only have abstract methods in their definition.
When an non abstract class is derived from an abstract class, the derived class provides the implementation of abstract methods by overriding them. The derived class methods should therefore include override keyword When a class implements an interface, the class dosent override the methods. Rather the methods are defined from the scratch. and so override keyword is not part of method header.
The derived class can override all or only a few abstract methods from the base class. The derived class can also be an abstract class The class that implements interface should provide concrete implementation for all the methods defined in interface
A class can extend one base class and implement multiple interfaces

Interfaces cannot be intatiated.
Interfaces dosent have constructors


What is an Abstract Class?

We usually think of classes as being complete definitions.  However, there are situations where complete definitions of a class is not possible.  In OO, we can create a class that have incomplete definitions ( we can define what methods should be there in the class, but not the definition of the method).  These  incompletly defined classes are called as Abstract Class. These incompletely defined classes are also very useful like completely defined classes.   We cannot create an instance of an Abstract Class (ie intansiated),  but with inheritance, abstract class enforces the derived class to have an implemention of methods that are declared abstract in base class.

A method with only method header and with no method body is called as Abstract Method.   A method with a method header and a method body is called as Concrete Method.

In abstract Class you can specify the method with only method header like in the following example

public abstract class BankAccount
      private string name;

     public void PrintName()  // Concrete Method
    public  abstract void printAccountType(); // Abstract Method


In the above class, note that the class is also declared abstract.  Whenever a class contains one or more abstract methods, then the class should be declared Abstract.  It is not necessary that an abstract class should only contain abstract methods.  It can also contain Concrete methods.

The methods which donot have a definintion (or method body) is defined using the keyword abstract as in the above example.

The derived class of abstract class should have a method implementation that are declared abstract in base class.  For exampe

public class SavingsAccount : BankAccount
         public  override void printAccountType()
              Console.WriteLine(" This is a savings account ");

Note : If the derived class does not provide concrete implementation of all the abstract methods that it  inherited from the abstract class,  the derived class will still be an abstract class. Only when the derived class provides concrete implementation of all the methods from the abstract class, can it be intantiated.

What is Polymorphism & How is it implemented?

Polymorphism refers to the ability of two or more objects belonging to different classes to resepond exactly to the same message in class specific ways.

Note : If you search the web for polymorphism, you will find many many definitions. I even read somewhere that overloading is also a kind of polymorphism.  But  a majority of the sites say the definition similar to the above.  So, I am sticking to it.  Remember there is no hard core definition for any of the object oriented concepts.  That is the problem why people run away from basics.

Example :   I would like to give two real time examples for polymorphism. 

1. School Bell.  Lets say that the final bell rings in a school/college.  What happens – a group of students go home, a group of students go to play ground, a group of students go to library and a group of stundents go to special classes.  What do professors do. A group of professors go home, a group of professors proceed to lab to continue their research, a group of professors do admin work etc.  The message ( ie school final bell) is same for all the objects (students & professors. note that professors and students are two different types of objects), but the way they respond depends on the object.   This is a very good example of polymorphsim

2. If you give an instruction "cut' to three different people – a hair stylist, a doctor and a movie actor. How do they respond.  The hair stylist cuts the hair.  A doctor will cut your body for surgery, a movie actor will stop acting. The message (cut) is same to all three objects ( actor, hair stylist and a doctor), but they threee respond in three different ways. This is called as polymorphism.

Inheritance with overriding facilitates polymorphism.  

Lets say that we have a base class called Class A and it has a overridable method called print which prints all the attributes.  Then by inheritance concept, all the dervied class will inherit this print method. The derived classes can either override the print method or use the print method from base class.  So, all the objects of base class and derived class have a method called print and they respond differently to a message based on its class implementation.

How is polymorphism implemented ?
 The fundamental idea of polymorphism is that a compiler doesnt know which method (ie base class implementation or derived class implementation of a method)  to call during  the compile time.  It only knows during run time ( based on the  object).   This is called as latebinding.  This type of polymorphism is called as "polymorphism by inheritance"

Polymorphism can also be achived through method overloading.  During the compile time itself the compiler knows which method to execute. This is known as early binding. 

What are Collections?

A collection object is an object that can hold multiple references of some other type of objects. Different collections in OO  

  • Array –  In C# arrays are objects.
  • Ordered lists  – similar to array. elements placed in a particular order and retrieved in same order
  • SortedList  – similar to ordered list. The elements are sorted when added to collection
  • Sets – unordered collection. (like throwing the marbles into bag. we dont know which will come out when we pick one.. order of retrival is not known). Important aspect of set is duplicates are not allowed.
  • Dictionaries (in C# HashTable) – provides a way for storing elements with a unique lookup key for the element.

User defined Collections :  You can create user defined collections using the inbuilt collection types.  Just like you use basic datatypes to create a user defined data type, you can use the inbuilt collections to build user defined collections.

Collections of SuperTypes :    Array is sequence of memory locations where elements of same type are stored.  This is true for an array of string, int or some other primitive datatypes.  But for storing the references of the objects (instances of classes), the rules are bit different.  The rules are different because  of the power of inheritance.   It turns out that if we create an array of baseclass (lets call it Class A), then the array can store the references of objects of base class (ie Class A) and all the derived class of the base class. 

In C# only arrays allow us to specify the type of class (ie type of array)  . All other collection types dosent  allow us to  specify the type. Most collections in C# are designed to hold the type System.Object (which is the base class for all the collections for both user defined and in-built datatypes) . So you can put any type of  objects into collections in any order.

What is Inheritance, Overriding,OverLoading ?

Inheritance is the process of creating a new class from one or more existing class.  In otherwords, a new class acquires the qualities of existing class.

Example.  Lets say that we need to model a bank account.  Lets say that the bank has only two types of account  – Savings Account and Current Account.  Both of these accounts have some charateristics in common.  So, we define a class based on common charateristics called BankAccount.   Now to create a class called for SavingsAccount / CurrentAccount, we can derive/inherit the fetaures of BankAccount. This is known as inhertitance.   BankAccount is called base class/ super class.  SavingsAccount/CurrentAccount is called as derived class / sub class

Inheritance can be single (only one base class) or multiple (two or more base class)).   C# supports only single Inheritance.  Multiple  inheritance is not support in C#.  To achieve multiple inheritance in C# we need to use Interfaces

Inheritance in C# is indicated by the following syntax

<access modifier><classname> : <baseClassName>

Example : public class SavingsAccount : BankAccount { // declare the additional info needed for savings account}

In Inheritance, what ever is true for BaseClass is also true for derived class.  For example, all the attributes and member functions in baseclass  – BankAccount  is also true for derived class -SavingsAccount .

Since derived classes are special category of base class, its called as specialization.  In otherwords, specialization is the process of defining a new class based on definition of existing class.  Generalization  is the term used to refer the baseclass (ie recognizing the common features of several existing classes and creating a common base class for all of them) . 

Inheritacne is based on accessibility of the baseclass.  All public members are inherited to derived class. But there is some complexities in inheriting other accessibility types.  We will discuss them later. 

Inheritance is also called as relationship between classes.  It is different from that of Aggregation and Association.  It differs at the object level.  While Association and aggregation is between individual objects,  Inheritance on the other hand is the way of describing a single object.  ie with Inheritance, an object is simultaneously an instance of derived class and all of its base classe(s).

Note : In C# System.Object class serves as the base class for both user-defined and in-built datatypes.  We will discuss about Object class in seperate post.

The single most important advantage of Inheritance is Reusability. There are many other advantages like creating a new derived class as and when required with out affecting the base class (which will be of great benifit in software development where requirements keepi changing every now and then).

If we want the derived class to have a different implementation of a method than that of base class, then we use a concept called as Overriding.  In otherwords customizing the way that a derived class performs a service—that is, how it responds to a given message—as compared with the way that its base class would have responded to the same message, is accomplished via a technique known as overriding

Overriding  means changing the methods implementation in derived class without changing the interface or method signature.  In order to override a method in C#, the method to be overridden has to be declared virtual  in the base class using the virtual keyword.  Declaring a method a virtual means, it may be (but its not necessary) overriden in the derived class.   The derived class has to then override the method using override keyword in the derived class method implementation.  The overriddent method in the dervided class should have the same return type and method signature.

public class BankAccount   // this is the base class in our example
 private string firstName;
 private string lastName;
 public virtual string getFullName()
  return  lastName + firstName;

public Class SavingsAccount: BankAccount  // this is the derived class in our example

 public override string getFullName()
  return lastName + ", " + firstNAme;

 Overloading  :  Overloading allows two or more methods in the same class to have a same name with different parameter list.
public void Draw(int x, int y);
public void Draw(int x, int y, int z);

Note : Constructors are overloaded and they are NOT OVERRIDDEN.

Are programmers blind?

This  is one of the stories which every one knows.  Once a couple of blind men,  in-order to understand an Elephant, went to a zoo.  Each went and touched the Elephant and got a feel of it.  They went back home and started to write about Elephant in their own experience.  The blind man who touched the body of the elephant concluded that elephants are like huge walls.  The blind man who touched the Elephants tail concluded that elephants resemble ropes.  The blind man who touched Elephants leg concluded that Elephants are like trees.  According to each of them, they are right. But the truth is – "Elephant is all of them". Only if a blind man touches all of these, can understand an elephant. Otherwise, they will only make assumptions and conclusions.

We programmers are no different than blind men.  We learn one aspect of the technology ( even if you know how to write a "Hello World" program, you call yourself a techologist in that area) and think that we are professionals without understanding the important aspect of the technology (or software development for that matter) .  I am now trying to get a feel of complete software development.  I know its really a tough job. But, I have taken a step and am confident that I will be a better developer than I am now in sometime . I am working on it and if you read my blog,  you will notice that I am doing something to understand the technology rather software development starting ground up.

What are associations, links and aggregations?

Association is the relationship between two classes. When the association is between two classes, its called Binary Association.  When the association is between two instances of the same class, then its called  reflexive or unary association.
Example : Binary Association :  Employee works for Employee
                Unary Association: A Employee supervises Employees

For a given association between object A and object B,  there can be three possible categories (the following are called mutiplicity).

  1. One to One.  Exactly one instance of Class A is associated with exactly one instance of Class B and vice versa.  Example: A department has exactly one Head and One Head can lead only one departmet
  2. One to Many : One instance of Class A can have many instance of Class B.  From perspective of Class B, there can be only one Class A  Example : A department employees many Professors, but a professor works only for one department
  3. Many to Many :  For a given instance of Class A there can be many instance of Class B and From Class B perspective there can be many instances of Class A.  Example : A student enrolls in many courses and a course has many students

Link is the relationship between two objects. There are no multiplicity concepts in links.  Links always exists between two objects.


Link :  Azagu works for Company-xxx

Aggregation : Aggregation is a special type of association or otherwise called as "Consists of " or " has a " or " is composed of " relationship.   Like an association, aggregation is used to reprsent relationship between two classes.  But with Aggregation we are representing to more number of relationship.  Example,  A car is composed of engine, gear, wheels etc.

What is an Instance constructor?

Instance Constructor is a speical type of  method in a class which have the same name as a class that gets executed when a new instance (object) of a class is creaetd.

Student s = new Student();

In the above line, C# compiler actually calls the constructor of Student class to create an instance.  The constructor allocates the required memory and returns the reference of the memory.

Strictly speaking constructors are not methods (you cannot invoke a constructor with a dot notation). Constructors are executed when the object is instantiated.  If there are no constructors specified in the class, then C# by definition automatically provides a parameterless constructor to the class which initializes the data members to zero-equivalent values.  There can be any number of constructors in a class (but the parameter list should vary).

Points to Remember when you are writing a constructor

  • Constructors dont have return type
  • Constructor name should be same as the class name
  • Constructor cannot be invoked by dot notation. 
  • A class with only private constructors cannot be instantiated

There is something called as "Class Constructor" (also known as static constructors)  in .NET. We will discuss this in a seperate post.

A good article on Constructor can be found at Constructors

What are Accessors(Properties)? Whats the power of Encapsulation?

As discussed in the previous posts, attributes are the information we gather about an object.   In real time projects,  we often restrict the access to these attributes for variety of reasons. One such reasons is data security ( we are not going to get into details of this).   These kinds of restrictions are called as Information Hiding

In a well designed object oriented  model, an object publicizes what it can do, ie what services  it can provide.  It will hide  the internal details like how its implemented,  how it performs the service etc.

In OO terminology, this is achieved through the concept called Accessibility. Accessibility determines if  the attribute/method is accessible outside of the class.  In  C#, the accessibility is achived by using the access modifier keyword  at the begining of the declaration. 

ex private int age; public string Name; public string GetFullName(); etc.

C# defines five tyes of accessibility. We will only list what they are.   We will discuss them in future

The accees modifier keywords in C# are

  1. private (attributes and methods are private by default)
  2. public
  3. protected
  4. internal
  5. protected internal

Methods of a class are typically declared public (there can also be private methods in a class).  The reason is that the class should publicize its service. On the other hand, the attributes of a calss are declared private (so that the object will have control over data) and give access to private attributes through public methodsThere are two ways of providing access to private attributes through pubilic methods.

  1. Get/Set methods
  2. Properties. C# prefers to go with properties way.  A property defines whats called as get accessor and set accessor.  Note that get and set accessors are not methods.

Get/Set are public methods that access the private variable.

Properites or get/set methods are called as Accessors.  ie, they are the methods that give access to objects private members.

public int GetAge(){
return age;
public int SetAge(int myAge){
age = myAge;

Property in C# behaves like accessing the public attributes.

public int Age{
       set { 
             age = value; // note that value  is implicitly declared variable.
          return age;

In client code,  we will access like 
         <objectName>.Age = 12;

The power of Encapsulation

We sofar have discussed that letting attribute values to  be accessed through public method is the best way of implementation.  It has the following advantages

  • Authorizied access to attributes – Some attributes are only accessible by the object itself, some are accessible to outside world
  • Data Integrity. you can have logics in get/set method that prevent aribitary setting of attributes. For example, if you have a date attribute inside your class, you can have logic inside get/set methods, that prevents any other values other than date to be set to the attribute
  • Hiding the implementation details.  Your method implenetation details are always hidden from the users of the service.  This means that you can change the method logic without affecting the users of the service.

What are methods,method headers, signatures, arguments, parameters etc., ?

In order to make use of the service provided by an object, one should know what object is capable of performing and how to request for the service.   Lets say an Object A wanted to use the service of Object B, then Object A should know what service(s) Object B provides and also should talk in Object B's language inorder to get the service.  This blog is about how behaviour (methods) are specified with in a class. 

Lets take a realworld example of getting  a service and compare it with the objects.  Lets say that you are going to Railway booking counter.  In order to get the service you will / should do the following

  1. First and foremost you should know what services are provided in railway booking counter.  Examples of services are a) An option to check the ticket availability in automattic teller machine, b) To book / Cancel a Ticket c) General Enquiry etc.  You cannot expect your favoirte dish to be served in Railway booking counters.   Similary, to get the services from an object, another object should know what are the services provided by the object.  
  2. You should speak the language of the ticket booking clerk. ie, if you want to book ticket, you got to fill in the application form (fill in your name, source and desingation of travel, your seat choice, train number, train name etc) and give it to the clerk.  You cannot go and ask the clerk "give me a ticket" (you know what response you get in railway booking counters) . Similarily, one shouuld communicate with objects by providing information in the way object expects in-order to get its service.
  3. The railway ticket clerk will issue a ticket if there is a seat available, else she will say "no tickets for mentioned train".  Similary, objects will perform the service and may or may not pass on the information back to the requestor.

 To summarize, object should publicize their service, the requestor should communicate with the object to get its service by providing additional information if required and finally the object will peform the service and may or many not notify the requestor.

In OO terminology these three aspects of an object's behaviour are taken care by defining a method header.  A method header is the formal specification of a behaviour of a object.  It gives information on how to invoke the object.  Its these methods that implements business logic of a system.

Note :  Before reading a couple of books on OO, I used to say "calling a method".  Its not the correct way to say. One should say as "invoking a method".  Its not a such a big thing but for me it is..

Ok, back to method headers.  A method header contains the following

  • Method Return type
  • Mehods accessibility modifiers  (We will discuss about this future)
  • Methods Name
  • An optional list of formal parameters seperated by comma ( specifying the type and name of parameter) enclosed in parenthesis

Example :

public                                 bool             IsEligibleForVoting     (  int iAge  )

Access modifier               return type   MethodName          Parameters            

Note : Methods need not always contain paramters. In such case the parathesis are left empty     

Method Signatures :  Method Headers with out return type, names of parameters are called as Method signature.  A method signature contains method name, order, types and number of parameters being passed to the method.

Example  Method Header   : long  AddTwoNumbers (int a, int b)

               Method Signature :  AddTwoNumbers(int, int)

What are Arugments and Parametes ?

Parameters Arguments
A paramete is a locally scoped variable declared in method header, that temporarirly comes to existence when the method is executed. Arguments are values that are passed to the method when they are invoked.
They are often interchanged in our programming world. Is there any big deal in the names? Yes, ofcourse. An Emigrant in one country is called as Imigrant in another coutnry, though they bother refer to the same person the level of freedom varies… so is case with parameters and arugmetns.

The purpose of the arguments is to pass information to methods.