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());
}
}
The override
keyword tells the compiler that this method was defined in the base class.
Summary for abstract && inheritance
- 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.
0 Comments:
Post a Comment