An Interface is the same as a class, it is a blueprint of a class. Just like any other class, an interface can have methods, properties, events, and indexers as its members. But unlike a class, the method in it is an abstract method (only method signature, contain no body).
- Interface is used to achieve abstraction and multiple inheritance which cannot be achieved through the class.
- An interface specifies what a class must do but not how to hence the abstraction.
- By deafult, the members of interface are public and abstract. It cannot have private members.
Declaring an interface
The keyword interface is used to declare an interface and is done just like a class as shown below.
1 2 3 4 5 6 7 | specifier interface interface_name { // declare Events // declare indexers // declare methods // declare properties } |
Example:
1 2 3 4 5 | public interface Animal { void animalSound(); void run(); } |
Implementation of an interface is done in the following way on a class.
1 2 | //implementing interface class className : interfaceName |
Example 1: C# program to illustrate interface
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | using System; public interface IAnimal { void sound(); } // implementing interface to class public class Dog: IAnimal { public void sound() { Console.WriteLine("The dog barks: woof woof"); } } //main class public class INterfaceMain { static void Main(string[] args) { Dog obj = new Dog(); obj.sound(); } } |
Output:
The dog barks: woof woof
Multiple Interface
We can create multiple interfaces in a program having different tasks and use them in the same class. And to implement multiple interfaces in the same class we separate them with commas in between as shown in the program below.
Example 2: C# program to illustrate multiple interface
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | using System; public interface IDog { void barks(); } public interface ICat { void meows(); } // implementing multiple interface to class public class Animal: IDog, ICat { public void barks() { Console.WriteLine("The Dog barks."); } public void meows() { Console.WriteLine("The Cat Meows."); } } //main class public class INterfaceMain { static void Main(string[] args) { Animal obj = new Animal(); obj.barks(); obj.meows(); } } |
Output:
The Dog barks.
The Cat Meows.