In post about abstraction abstract classes I used examples of method which implementation is defined in derived class. Here is when Interfaces comes in play. An interface contains only the signatures(declarations) of methods, properties, events or indexers. It looks like a class, but has no implementation. The reason interfaces only provide declarations is because they are inherited by classes and structs, which must provide an implementation for each interface member declared. It’s important to add that Class can inherit from multiple interfaces, but not multiple classes.
Since all interchangeable components implement the same interface, they can be used without any extra programming. The interface forces each component to expose specific public members that will be used in a certain way.
Interfaces are declared using the interface keyword. It is similar to class declaration. Interface statements are public by default. Interface declaration should have “I” prefix, it is programming habit, that informs user that this is not a class or anything else just by looking at its name:
public interface INewInterface { // interface members, public as default. Interfaces does not allow //explicit access modifiers. void Print(); double getNumber(); }
This is simple example of interface it does not contains any implementations. That’s why we need to provide it in derived class. Method signature must be the same in both cases.
- Interface can not contain fields
public class MyClass : INewInterface { private double number; //class constructor public MyClass() { number = 25.6; } public double getNumber() { return number; } public void Print() { Console.WriteLine("Transaction: {0}", number); } }
Here we provided the implementation of the methods, all signatures matches the Interface signatures, we can add fields and new methods in this class. This class must provide implementation of all methods, methods in interface inheritance chains as well.
class MainClass { static void Main(string[] args) { MyClass n1 = new MyClass(); n1.Print(); Console.ReadKey(); } }
Now we create instance of our class and execute the methods. Now you know entire process of interface implementation, it’s worth to remember that class can inherit multiple interfaces, and that we can not instantiate instance of an interface. In next topic We will take a look at the differences between interfaces and abstract classes. Stay Awesome!