illustrates inheriting from a class and implementing multiple interfaces

image_pdfimage_print

   

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example8_3.cs illustrates inheriting from a class and
  implementing multiple interfaces
*/

using System;


interface IDrivable
{

  // method declarations
  void Start();
  void Stop();

  // property declaration
  bool Started
  {
    get;
  }

}


interface ISteerable
{

  // method declarations
  void TurnLeft();
  void TurnRight();

}


class MotorVehicle
{

  // declare the field
  private string model;

  // define a constructor
  public MotorVehicle(string model)
  {
    this.model = model;
  }

  // declare a property
  public string Model
  {
    get
    {
      return model;
    }
    set
    {
      model = value;
    }
  }

}


// Car class inherits from the MotorVehicle class and
// implements the IDrivable and ISteerable interfaces
class Car : MotorVehicle, IDrivable, ISteerable
{

  // declare the underlying field used by the
  // Started property of the IDrivable interface
  private bool started = false;

  // define a constructor
  public Car(string model) :
  base(model)   // calls the base class constructor
  {
    // do nothing
  }

  // implement the Start() method of the IDrivable interface
  public void Start()
  {
    Console.WriteLine("car started");
    started = true;
  }

  // implement the Stop() methodof the IDrivable interface
  public void Stop()
  {
    Console.WriteLine("car stopped");
    started = false;
  }

  // implement the Started property of the IDrivable interface
  public bool Started
  {
    get
    {
      return started;
    }
  }

  // implement the TurnLeft() method of the ISteerable interface
  public void TurnLeft()
  {
    Console.WriteLine("car turning left");
  }
  
  // implement the TurnRight() method of the ISteerable interface
  public void TurnRight()
  {
    Console.WriteLine("car turning right");
  }

}


public class Example8_3
{

  public static void Main()
  {

    // create a Car object
    Car myCar = new Car("MR2");

    Console.WriteLine("myCar.Model = " + myCar.Model);

    // call myCar.Start()
    Console.WriteLine("Calling myCar.Start()");
    myCar.Start();

    // call myCar.TurnLeft()
    Console.WriteLine("Calling myCar.TurnLeft()");
    myCar.TurnLeft();

  }

}