Introduction
Inheritance is a way or technique by using one class, you can access details of other class. What happen if you want to access details of more than one class and implement them within the current class.
C# cannot have more than one super-class. We can only do this by using Interface.
class class-name : A, B , C
{
}
The above is not allowed in C#.
We also know that C# does not support multiple inheritance because by using this, it creates problems for developer but also creates a lot of confusion. To overcome this issue, C# supports multiple inheritance by using Interface.
An interface in C# is reference type. There are some major differences between class and interface:
- Interface members cannot be declared as
static
. - Interface cannot declare constructor and destructors.
- All members of an Interface default
public
and abstract
. - Interface methods are
abstract
so they do not include implementation of the method.
Structure of Interface
An Interface only defines the methods, properties, indexers and events but not their implementation. It is the responsibility of that class that implements the interface.
Interface name-of-interface {
(A)
Interface first-interface
{
int Addition( int x, int y);
}
(B)
Interface Second-interface
{
int Multiple( int a, int b);
}
In the first interface, there is only one method Addition
and in the second interface also, there is one method Multiple
.
(C)
Interface Third-interface
{
int Divide ( int c, int d) ;
}
What happens if the third interface inherits both of the A , B
interface?
Interface Third-interface : first-interface , Second-interface
{
int Divide ( int c, int d) ;
}
Now if one class inherits the third interface, then it automatically inherits both of the two interfaces first & second, and it is the responsibility of the class to implement their methods, otherwise it raises an error.
Class AccessInterface : first-interface , Second-interface , Third-interface
{
}
Name Collision with Interface
What happens when you inherit multiple interfaces and somewhere two or three or more interfaces have a common method name. Then it raises a voice of error. C# comes out in this situation with explicit interface implementation.
Example:
Interface A { void Name () };
Interface B { void Name () };
Class Access-Interface : A, B
{
public void Name( ) { } ;
}
With this technique, explicit interface implementation we access method by using name of the interface.
Interface A {
void Name( );
}
Interface B { void Name ( ) ;
}
Class AccessInterface : A , B
{ void A.Name( )
{
Console.writeline("Interface A method call "); }
void B.Name ( )
{
Console.writeline("Interface B method call "); }
}
For more information, visit http://professional-programmer-guide.blogspot.in.