Inheritance in C#

✓ Inheritance
The derived class inherits from the base class, and the methods in the base class become part of the derived class. In C#, a class is allowed to derive from one base class. It is not allowed to derive from two or more classes. However, unless DerivedClass is declared as sealed, you can create further derived classes that inherit from DerivedClass using the same syntax.

Inheritance applies only to classes, not structures. You cannot define your own inheritance hierarchy with structures, and you cannot define a structure that derives from a class or another structure.

//base class
class Vehicle
{
    public void StartEngine(string noiseToMakeWhenStarting)
    {
        Console.WriteLine("Starting engine: {0}", noiseToMakeWhenStarting);
    }
    public void StopEngine(string noiseToMakeWhenStopping)
    {
        Console.WriteLine("Stopping engine: {0}", noiseToMakeWhenStopping);
    }
    public virtual void Drive()
    {
        Console.WriteLine("Default implementation of the Drive method");
    }
}

//derived class
class Airplane : Vehicle
{
    public void TakeOff()
    {
        Console.WriteLine("Taking off");
    }
    public void Land()
    {
        Console.WriteLine("Landing");
    }
    public override void Drive()
    {
        Console.WriteLine("Flying");
    }
}

//derived class
class Car : Vehicle
{
    public void Accelerate()
    {
        Console.WriteLine("Accelerating");
    }
    public void Brake()
    {
        Console.WriteLine("Braking");
    }
    public override void Drive()
    {
        Console.WriteLine("Motoring");
    }
}

// Using the inherited class
Console.WriteLine("Journey by airplane:");
Airplane myPlane = new Airplane();
myPlane.StartEngine("Contact");
myPlane.TakeOff();
myPlane.Drive();
myPlane.Land();
myPlane.StopEngine("Whirr");

Console.WriteLine("\nJourney by car:");
Car myCar = new Car();
myCar.StartEngine("Brm brm");
myCar.Accelerate();
myCar.Drive();
myCar.Brake();
myCar.StopEngine("Phut phut");

✓ Public vs private vs protected access
Public fields and methods of a class are accessible to everyone, whereas private fields and methods of a class are accessible to only the class itself.

You can access a protected base class member not only in a derived class but also in classes derived from the derived class. A protected base class member retains its protected accessibility in a derived class and is accessible to further derived classes.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s