|Deep C# - Inheritance|
|Written by MIke James|
|Thursday, 27 August 2020|
Page 4 of 4
To be clear:
What good does this do?
The role of interfaces in object-oriented programming, indeed whether they have a role, is something that can be discussed at length without coming to any strong conclusion.
An interface is very similar to the idea of a pure abstract class. If you declare a class as abstract then any methods that are also declared as abstract don’t have definitions and have to be overridden by any class that inherits the abstract class – unless it too is declared to be abstract. An abstract class can’t be used to create objects and it only becomes “non-abstract” when all of the abstract methods have been overridden.
You can see that abstract classes allow the definition of an inheritance chain that adds more implementation code at each step. An interface on the other hand demands that every method it declares is implemented the very first time it is inherited – in this sense it’s a much cruder instrument.
The intended use of an interface is to ensure that all classes that inherit from it have the methods that it declares. If a class doesn’t implement all of the interface methods exactly then the class doesn’t compile. You can think of it as a template for a class and its use is to ensure that classes present a uniform and enforced set of methods that can be used with confidence by other objects. Used in this way it is a central part of most modern programming methodologies.
One big difference between class and Interface inheritance is that Interfaces support multiple inheritance. You can force a class to implement two Interface specifications using
public class MyClass:IMyInterface1,
This looks like multiple inheritance but as nothing but the method definitions are inherited it isn’t nearly so dangerous or, of course, as useful!
Some other facts worth knowing about interfaces are that a struct can inherit an interface and an interface can inherit from other interfaces. Of course an interface that inherits from another set of interfaces doesn’t have to implement anything and it simply serves to extend or add to the base interfaces.
or email your comment to: email@example.com
|Last Updated ( Thursday, 27 August 2020 )|