Tuesday 8 July 2014

Interfaces and Abstract Classes

Interfaces and Abstract Classes
Interfaces : Nothing but declaration, no implementation. Contains only Abstract methods.
Ex:
public interface IVehicle
{
void Start();
void Drive();
void Park();
void ChangeGear(int gear);
void SwitchOff();
}
In order to implement the interface, every method must be implemented in the class, else a compiler error will ensue
public class Vehicle : IVehicle
{
public void Start()
{
Console.WriteLine("The vehicle has been started");
}
public void Drive()
{
Console.WriteLine("The vehicle is being driven");
}
public void Park()
{
Console.WriteLine("The vehicle is being parked");
}
public void ChangeGear(int gear)
{
Console.WriteLine("Gear changed to " + gear.ToString());
}
public void SwitchOff()
{
Console.WriteLine("The vehicle has been switched off");
}
}
Abstract classes: Can have some implementation and some non implementation methods like interface.
public abstract class Vehicle
{
public void Start()
{
Console.WriteLine("The vehicle has been started");
}
public abstract void Drive();
public abstract void Park();
public abstract void ChangeGear(int gear);
public void SwitchOff()
{
Console.WriteLine("The vehicle has been switched off");
}
}
So each class that inherits from Vehicle will already be able to use the methods Start and SwitchOff, but they must implement Drive, Park and ChangeGear.
So if we were to implement a Car class, it may look something like this.
public class Car : Vehicle
{
public Car()
{
}
public override void Drive()
{
Console.WriteLine("The car is being driven");
}
public override void Park()
{
Console.WriteLine("The car is being parked");
}
public override void ChangeGear(int gear)
{
Console.WriteLine("The car changed gear changed to " + gear.ToString());
}
}
The override keyword tells the compiler that this method was defined in the base class.

Summary

  • An Interface cannot implement methods.
  • An abstract class can implement methods.

  • An Interface can only inherit from another Interface.
  • An abstract class can inherit from a class and one or more interfaces.

  • An Interface cannot contain fields.
  • An abstract class can contain fields.

  • An Interface can contain property definitions.
  • An abstract class can implement a property.

  • An Interface cannot contain constructors or destructors.
  • An abstract class can contain constructors or destructors.

  • An Interface can be inherited from by structures.
  • An abstract class cannot be inherited from by structures.

  • An Interface can support multiple inheritance.
  • An abstract class cannot support multiple inheritance.