An interface defines a contract that specifies functionality without implementation. It defines a set of methods that classes implement. Interfaces allow for multiple inheritance by allowing a class to implement multiple interfaces. Interfaces cannot contain data members, constructors, destructors, or static members. Both interfaces and abstract classes cannot be instantiated but interfaces only define method signatures while abstract classes can contain implementations. A class implements an interface by listing the interface name after the class name and providing implementations for all interface methods.
2. Interface
An interface is a purely logical construct that describes
functionality without specifying implementation
An interface generally defines set of methods that will
be implemented by the class
But interface doesn’t implement any method itself
interface
“What must be done not how it is
to done”
3. Why there is a need of interface
Multiple inheritance not allowed in c#
Base1
Base 2
Derived
So solution of this is implementing interface as
class can implement any no of interfaces in it.
4. Limitations of interface
Interfaces cannot have data members.
They cannot define constructors, destructors .
No member can be declared static.
Difference and similarities between interface and
abstract class
Similarities
Neither can be instantiated
Neither can be sealed
Differences
Interfaces cannot contain any implementation
Interfaces cannot declare non-public members
Interfaces cannot extend non-interfaces
5. Syntax for defining interface in C#
interface Interface- name{
ref-type method-name1(param-list);
ref-type method-name2(param-list);
//…
ref-type method-name N(param-list);
}
They
are essentially abstract methods.
methods declared in interface are implicitly
public,,no explicit access specifier is allowed.
6. IMPLEMENTING INTERFACE
General form of class implementing interface
Class class-name : interface-name
{
// class body
}
Things to be noted
When a class is implementing interface it has to
implement the entire interface ..it cannot pick and choose
which part to be implemented.
A class can implement more than one interfaces
separated by comma .
A class can inherit base class and with the combination of
interfaces ,,,but name of the base class will come first.
7. A SAMPLE PROGRAM
class Demo : abc
{
public static void Main()
{
System.Console.WriteLine("Hello Interfaces");
Demo refDemo = new Demo();
refDemo.xyz();
Sample refSample = new Sample();
refSample.xyz();
}
public void xyz()
{
System.Console.WriteLine("In Demo :: xyz");
}
}
8. interface abc {
void xyz();
} class Sample : abc
{
public void xyz() {
System.Console.WriteLine("In Sample :: xyz");
}
}
Output
In Demo :: xyz In Sample :: xyz