In the article before this I explained Abstract Classes.
Interfaces can contain only abstract members in it.
Non Abstract Class:
Only Non abstract members
Abstract Class:
Both Abstract and Non abstract members
Interface:
Only Abstract Members.
An Interface can be used for 2 reasons:
- Development of distributed application
- They support multiple inheritance
Class can have only one immediate parent class whereas it can have any number of interfaces as its parent.
An Inheritance can be one of 2 categories
- Implementation Inheritance
- Interface Inheritance
An inheritance that is achieved by inheriting from a class is implementation inheritance. This is single under Java and .Net languages.
Inheritance achieved by inheriting from an interface is interface inheritance. This is multiple in all languages.
- Default scope for members of interface is public
- Every member of an interface by default is an abstract
- Interface can't contain variable declarations in it
- As a class can inherit from another class or interface, in the same way an interface can inherit from another interface but not a class
Add interface under project as inter1.cs and write the following:
Interface inter1
{
Void add(int x, int y);
Void sub(int x, int y);
Void test();
}
Add interface interface2.cs and write the following:
Interface inter2
{
Void mul(int x, int y);
Void div(int x, int y);
Void test();
}
Add class interclass.cs and write following
Class interface:inter1,inter2
{
public void add(int x, inty)
{
Console.writeline(x+y);
}
public void sub(int x, inty)
{
Console.writeline(x-y);
}
public void mul(int x, inty)
{
Console.writeline(x*y);
}
public void div(int x, inty)
{
Console.writeline(x/y);
}
Void inter1.test()
{
Console.writeline("method of interface1");
}
Void inter2.test()
{
Console.writeline("method of interface2");
}
Static void main()
{
Interclass c=new interclass();
c.add(1,2); c.sub(2,2); c.mul(1,2); c.add(1,2);
c.div(4,2);
interi1=c; interi2=c;
i1.test(); i2.test();
console.readline();
Earlier we have discussed multiple inheritance; it is not supported in Java and .Net languages because of ambiguity problem but in the case of an interface we do not have an ambiguity problem even if the same method is defined under multiple interfaces and implemented in a class. The problem in an interface can be resolved in two ways:
- Implement each method separately for each interface under class by prefixing method with interface name but while calling method we need to call only the method with only a reference of the interface as we have done in our example
- Implement a method only under class where each interface thinks its own method is implemented. In this case we also can invoke a method directly by using object of class.
If we do not want to implement using an interface name then:
Public void test()
{
Console.writeline("declare under multiple methods");
}
Under main
c.test();