An interface is like an abstract class which allows the derived class to inherit more than one interfaces into it.
We have already seen an abstract class can have methods with or without implementation. But an interface can only have members without implementation. So it provides only structure of the objects like abstract class.
To implement an interface in VB.NET, we use the keyword Implements and we must provide implementations for all the methods of the interface we implements.
Defining an Interface:- Interfaces are declared with the following structure
Public Interface <Name of the interface>
:
<decleration of memebrs of the interface, means methods and properties
structure>
:
End Interface
Let us take up a example and see how the declaration been done
Interface IShape
Sub Draw(ByVal coord() As ArrayList)
End Interface
interface IShape
{
void Draw(ArrayList coord);
}
Implementation of Interface:- Interfaces are implemented using Implements keyword. All the members of the interface are implemented with Implements keyword.
“To implement a interface, we must implement all the methods and properties defined by the
interface”
If more than one interface is to be implemented, then interfaces names should separated by commas with the implements keyword while defining a class.
Lets us take an example of implementation:-
Public Class Drawing
Implements Ishape
Public Sub Draw(ByVal parCoord() As ArrayList) Console.Write("Draw a Circle")
End Sub
End Class
Public Class Drawing: Ishape
{
Public void Draw (ArrayList parCoord)
{
Console.Write("Draw a Circle");
}
}
In the example, we are implementing Isahpe interface, which contains Draw method into the Drawing Class.
Difference between Abstract class and Interfaces
When to use the interfaces in programming?
Solution:- The situation at which we need to implement the functionalities of two or more objects into one derived object. So it makes the derived object to refer to the interface methods and properties for syntax verification.