Code Heaven For C# Developer

Monday, February 8, 2010

Abstract classes

Like an interface, you cannot implement an instance of an abstract class, however you can implement methods, fields, and properties in the abstract class that can be used by the child class.

For example, we could create an abstract class for all vehicle to inherit from:


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());
}
}

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home