Interface in C#

Abhisek
Posted by in C# category on for Beginner level | Views : 7019 red flag

This article describes about the use of Interface in C#.
What is an 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.



Syntax to declare interface


interface NAME
{
final static datamembers;
methods;
}


Syntax to declare a child


class CHILD:Interface Class
{
//defination of methods of interface class
}


See the following sample program with one interface and two child implementing 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 



Page copy protected against web site content infringement by Copyscape

About the Author

Abhisek
Full Name: Abhisek Panda
Member Level: Bronze
Member Status: Member
Member Since: 10/11/2009 6:25:59 AM
Country: India
Abhisek Panda

Thanks and Regards Abhisek Panda Go Green And Save Your Future

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)