Loading...

Concept and Use of Interface in OOP C#, Step by Step Tutorial

Interface:

Interface is just like a front end, It describes "What" that what is done in the application but doesnot descreibe "How" that howthe methods are implemented.

Interface can be easily understood by following point:
  •       Interfaces are defined using the interface keyword. An interface cannot contain fields.
  •      Interfaces members are automatically public, we cannot use any access modifier.
  •       Within the interface, methods cannot have definition(body). 
  •       Interfaces and interface members are abstract; interfaces do not provide a default implementation.
  •       An interface can inherit from one or more base interfaces.
  •       To implement an interface member, the corresponding member on the class must be public, non-static, and have the same name and signature as the interface member.
  •        An interface cannot inherit a class.
  •        An interface cannot be instantiated directly.

Example of Interfaces in C#:


interface IPower  // Our Interface
{
    void On(); // methods which describe only "What", "How" is describe in Implementer Classes
    void Off();
}

class AirCondition : IPower // This is Implementor Class which is inheriting Interface IPower.
{
    public void On() //Implementation of method On() of Interface Ipower
    {
        Console.WriteLine("AirCondition.On()");
    }
    public void Off()  //Implementation of method Off() of Interface Ipower
    {
        Console.WriteLine("AirCondition.Off()");
    }
}

class Bulb : IPower  // This is Another Implementor Class which is inheriting Interface IPower.
{
    public void On()  //Implementation of method Off() of Interface Ipower
    {
        Console.WriteLine("Bulb.On()");
    }
    public void Off()  //Implementation of method Off() of Interface Ipower
    {
        Console.WriteLine("Bulb.Off()");
    }
}

class Program
{
    static void Main(string[] args)
    {
         IPower  device_b = new Bulb();  // making object using class Bulb
              IPower  device_a = new AirCondition();   // making object using class AirConditioner

              device_a.On();  // This will run On() method of Aircondition Class
              device_a.Off();   // This will run Off() method of Aircondition Class
              device_b.On();   // This will run On() method of Bulb Class
              device_b.Off();   // This will run Off() method of Bulb Class
    }
}


Output:




Thank You for Reading, Like this if you Understood, It Help a lot

Google+

 
TOP