Tuesday 13 September 2011

What Is Interface And Why We Use It?

Interface is simply like a class in OOP(Object Oriented Programming)In which we only declare the functions, properties, events and indexers but not defined that.Interface cannot contain fields. Implementation of all members (functions, properties, events and indexers) of interface must be given in a class which is derived from it.
Very common question is that why we use interface? Answered after some examples so it is more understandable.

Sample Example of Interface:

public interface IA
{
void Add();
int Count { get; }
event MYEvent Changed;
string this[int index] { get; set; }
}

Point to be noted that that there is no access modifies in any of the function or other members of interface in above example. Because declaring member in interface must be without access modifier and when we implement these members in derived class they all must declare as a public otherwise compile error occurs.

Complete Sample Example:

interface IA
{
void Method1();                     //Declare function without definition
void Method2(int i);                //Declare function without definition
}

class Implement_IA : IA       //Derived class of IA so it must implemts all members of interface IA
{
public void Method1()            //Implement method1 of IA must be public
{//....Do Some Work} 

public void Method2(int i)       //Implement method2 of IA must be public
{ //....Do Some Work }

public void ClassOwnMethod(string str)   //This is class own method
{ //....Do Some Work} 

}
public static void Main()
{

//Use of Methods is normal as we use

Implement_IA obj = new Implement_IA ();
obj.ClassOwnMethod("String");
obj.Method1();
obj.Method2(10);
}

In above example we made interface “IA” declare two methods,One class “Implement_IA ” inherit from “IA” and implements methods of interface and contain one its own method.

Why we use interface and purpose of interface?

Now come to question what is the purpose of interface and why we use it.
It is understand by the following phenomenon: 

Human beings have same structure of skeleton. But Outer Covering is different of each human. So consider skeleton as an interface and Outer Covering as class .All Outer Covering of human beings (Classes) inherits from same skeleton (Interface) and implement different functionalities according to that each human is differen from other.
Similarly all types of horses has same skeleton (Interface) but each horse is different from another on the basis of colour,cast etc same as defined above.

So this is the purpose of interface that it provides the structure of a scenario. For example we have to make method of numeric series so we made interface and declare method of series. Now if  we want series of numbers odd, even, multiple of 3, Etc. we implement the same method with different implementation according to type of series. 

Here is one Example:

interface IAnimal
{
void speak();
}
class Cow : IAnimal
{
public void speak()
{      //Implementation of Speak according to Cow           }
}
class Horse : IAnimal
public void speak() 
{       //Implementation of Speak according to Horse       }
}
public static void Main()
{
Cow objCow = new Cow();
Horse objHorse = new Horse();

//Calling same function with different implementations

objCow.speak();
objHorse.speak();
}

So in above example “Speak” function is implementing two times one for “Horse” and one for “Cow”. It can be say that Interfaces have no work without Class or Structure. 
Take a look diagrammatically

Now hope you understand why we use interfaces and what the purpose of it.

FAQ:

1) Can we create object of interface?

No! Object of interface cannot be created because it is only structure it has no implementation of anything only declaration, Second it has no constructor as well so it cannot be instantiate.
However we made object of interface by instantiating it to the derived class
Example 

Interface IA{ }

Class B:IA{ }

Main()
{
IA obj=new B();
//or
B objB=new B();
IA obj=objB;
}

2) Can Interface derived from other interface?

Yes! Inheritance between interfaces is allowed

Example:

Interface IA{ }
Interface IB:IA{ } 
However when class derived from interface “IB” so it must give implementation of “IA” and “IB” both.

3) How implement Multiple Inheritance in interfaces?

Multiple inheritances is allowed in Interfaces in C#

For example:

Interface IA{ }
Interface IB { } 

Class MyClass:IA,IB //here we inherit class from two interfaces
{
//Class must implement both interfaces IA and IB
}

Please feel free to ask.
Any corrections must be appreciable.
Thank You
hope it helps!

Happy Coding :)



15 comments:

  1. Very good article...my about interfaces and problem why we use interfaces is solve and increses.
    Thanks for Share.

    ReplyDelete
  2. 1-why there is no access modifier in interface for any item? b/c by default these are public and abstract. and when method implementing in sibling class the signature of method must include overriding.

    2-if there is a need in class which inheriting/implementing a interface and do not want to implement all the method of interface
    in sibling class so it can be possible and that sibling class will be said abstract class.

    3-interface object cannot be created or initialize only variable can be declar which type can be interface (that variable is not a object).

    4- inheriting of interface into class is as same as inheriting a class b/c both have a same meaning "is a" relationship. remember this.

    ReplyDelete
  3. Sorry to say but override use in sibbling class when we inherit from abstract class.


    Abstract class is my next topic!
    but
    you explained It :)
    any way
    Thanks for response Haider bhai :)

    ReplyDelete
  4. yes dear you are right override is not used in implementing method of interface in sibling classes.

    thanks for reply dear.

    ReplyDelete
  5. Good dear ....very nice article to me to understand the interface plz share some knowledge about abstract classes...

    ReplyDelete
  6. Thanks! Please vote for abstract class then...

    ReplyDelete
  7. brilliant work dude!!! keep up the good work!!!

    ReplyDelete
  8. That's good info....Keep it up!
    I have been waiting for next topic "Abstract class".

    ReplyDelete
  9. interface IA
    {
    Public Void MethodA(){……}
    }

    interface IB:IA
    {
    }

    interface IC:IA
    {
    }

    Class BC: IB, IC
    {
    }

    public static void Main (string[] argc)
    {
    BC obj=new BC();
    }

    how does the compiler get to know whether the call to MethodA refers to the copy of “IB” interface or refers to the copy of “IC” inteface?
    this is not allow in classes so how it is allowed in interface? can you clear my confusion?

    ReplyDelete
  10. Dear faz Correct form of your code is write below.
    interface IA
    {
    void MethodA();
    }

    interface IB : IA
    {
    }

    interface IC : IA
    {
    }

    class BC : IB, IC
    {
    public void MethodA() { }
    }

    public static void Main (string[] argc)
    {
    BC obj=new BC();
    }

    Now come to your question,You think in a wrong direction interface has not its own memory it is like a structure.So in your case you have to implement the interface "IA" method in your "BC" class so when yo made object of "BC" class the "methodA" is call from it self because it contained methods definition in its own class.

    ReplyDelete