- Back to Home »
- C#.NET »
- C#.NET Interface
Posted by :
Sudhir Chekuri
Saturday, 9 January 2016
- Interface is a collection of "abstract methods".
- All the methods in interface will be abstract methods.
- A class inheriting interface should implement abstract methods present in that interface.
- Multiple inheritance is possible in interfaces.
- Body of the abstract method should be given in the inherited classes.
- All the methods in interface are by default Public and Abstract.
interface interfacename
{
body
}
Example Program using interface
using System;
namespace interfaces
{
class Program : abc
{
static void Main(string[] args)
{
Program p = new Program();
p.add();
Console.ReadKey();
}
//implementing method in interface
public void add()
{
Console.WriteLine("add method");
}
}
interface abc
{
//by default public and abstract
void add();
}
}
add method
Inheriting Multiple interfaces
- It is one type of interface.
- It consists of multiple methods and multiple interfaces.
- To inherit multiple interfaces,use inheritance concept.
Program
using System;
namespace interfaces
{
class Program : abc, def
{
static void Main(string[] args)
{
Program p = new Program();
p.add();
p.sub();
Console.ReadKey();
}
//implementing method in interface
public void add()
{
Console.WriteLine("add method");
}
public void sub()
{
Console.WriteLine("sub method");
}
}
interface abc
{
//by default public and abstract
void add();
}
interface def
{
//by default public and abstract
void sub();
}
}
Output
add method
sub method
Example for Inheriting Multiple interfaces and implementing both methods with same name in derived class
Program
using System;
namespace Interfaces
{
class Program
{
static void Main(string[] args)
{
a x = new c();
x.Add();//AdditionA
b y = new c();
y.Add();//AdditionB
Console.ReadKey();
}
}
interface a
{
void Add();
}
interface b
{
void Add();
}
class c : a, b
{
void a.Add()
{
Console.WriteLine("AdditionA");
}
void b.Add()
{
Console.WriteLine("AdditionB");
}
}
}
OutputAdditionA
AdditionB