Interface is a contract that defines signature of functionality.
We create an interface using interface keyword. Just like a class contain properties, methods, events and delegates, But only declaration and no implementation.
For example we have an interface called ICustomer and inside that i have a method called scan. If we give a body to the method we will get an error stated that “interface members cannot have a definition”.So interface members have only declaration and no implementation.
And also interface members are public by default, and they don’t allow explicit access modifiers.we can see it in below picture.The Error state that “The modifier public is not valid for this item.”
Also interface does not contain fields. When you pass fields to an interface it gives you error state that “Interface cannot contain fields.”
Lets go head now we will create an class Customer. If Customer Class inherits from an interface, it must provide implementation for all the interface members. If not we will get an compiler error. We can see it in below picture that on compile time it gave you an error.
The error says that you need provide implementation for all the members of an interface.
So above picture we can see that in an interface contains two methods and when class inherit an interface and also provides an implementation.
Now we create an instances of the class customer and try to run the code snippet and lets see what will be the output.
So here is the output in the above picture .
Important point :- We cannot create an instance of interface because its a half code there is no implementation. But an interface reference variable can point to derived class object.
In Below Picture we will see how it point to interface reference variable of derived class object.
Lets go head and see if we have two interface like ICustomer1 and ICustomer2 inside there will be some methods. We can see it below picture
when class inherits the interfaces it inherits both the interfaces .
Also we need to provide implementations for both the methods from an interface
if we don’t want to inherit both the interface in that case what we can do first ICustomer2 will inherit ICustomer1 like this in below picture.
Then class Customer will inherit ICustomer2 and implements methods of two interface.
If we run this will get same output like in previous picture. So here ends the basic of interface in next article we will see Explicit interfaces implementation.
If you are new to programming then one of the best way is to learn programming with project following we have one such video which demonstrate practical using C# and .NET: -