Difference between abstract classes and interfaces in C#
Abstract classes allow for other classes to be derived from it. However, an instantiation of the base class type (i.e. the abstract class) cannot be done. To declare a class abstract, place the word 'abstract' between the access modifiers and the class keyword.
Example:
public abstract class Vehicle
{
}
Within abstract classes you can have
- Data field members (such as properties)
- Regular Methods - and -
- Abstract Methods
Abstract Methods do not include a body in them. Instead the way they are implemented is defined the class that is derived from the abstract class. The derived class must have an implementation method for every abstract method in the base class.
Abstract methods are written as follows:
public abstract class Vehicle
{
:
public abstract double GetMileage(); // does not have a body enclosed in curly braces
:
}
Interfaces
Interfaces are like abstract classes with pure abstract methods. That is, if a class is derived from an interface, every method declared in the interface must have a way to be implemented in the derived class. Interfaces only specify signatures for the members they contain (such as methods, properties and events). Writing an interface is essentially the same as writing a class, except that your members have no bodies and you replace the word class with interface.
Example:
public interface IAutomobile
{
double MilesPerGallon;
string MfgLocation;
}