Use of interface in C#

Abhisek
Posted by Abhisek under C# category on | Views : 2147
Interface:-


Interface is the collection of abstract method that are implemented in different applications. It is defined as the process of defining once and use it when and where we want to implement.

It defines derivation of new classes from more than one super class, that means by using interface we can implement multiple inheritance.

Interface can not be instantiated but can have reference variable . Interface can contain only final and static datamembers as well as methods of abstract type , it means the methods have to be overridden by child .

There is an interface means there must be a child class which has to override all the methods of interface. If it will not override completely the it should be abstract class and offers to form concrete class to override.

See the following sample program with one interface and two child implemeting the interface class.



interface Area
{
double Get(double x, double y);
}

class Circle:Area
{
//overriding interface method
public double Get(double x, double y)
{
return 3.14* x * x;
}
}

class Rect:Area
{
//overriding interface method
public double Get(double x, double y)
{
return x * y;
}
}

class InterfaceDemo
{
static void Main(string[] args)
{
//creating objects of child class
Rect r = new Rect();
Circle c = new Circle();
double k = r.Get(10.2, 12.9);
double l = c.Get(5.0,0);
Console.WriteLine("Area of rect= {0}", k);
Console.WriteLine("Area of circle= {0}", l);
}
}


OUTPUT

Area of rect=131.58
Area of circle=78.5

Comments or Responses

Login to post response