illustrates polymorphism

image_pdfimage_print

   

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

Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example7_2.cs illustrates polymorphism
*/

using System;


// declare the MotorVehicle class
class MotorVehicle
{

  // declare the fields
  public string make;
  public string model;

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

  // define the Accelerate() method (may be overridden in a
  // derived class)
  public virtual void Accelerate()
  {
    Console.WriteLine(model + " accelerating");
  }

}


// declare the Car class (derived from MotorVehicle)
class Car : MotorVehicle
{

  // define a constructor
  public Car(string make, string model) :
  base(make, model)
  {
    // do nothing
  }

  // override the base class Accelerate() method
  public override void Accelerate()
  {
    Console.WriteLine("Pushing gas pedal of " + model);
    base.Accelerate();  // calls the Accelerate() method in the base class
  }

}


// declare the Motorcycle class (derived from MotorVehicle)
class Motorcycle : MotorVehicle
{

  // define a constructor
  public Motorcycle(string make, string model) :
  base(make, model)
  {
    // do nothing
  }

  // override the base class Accelerate() method
  public override void Accelerate()
  {
    Console.WriteLine("Twisting throttle of " + model);
    base.Accelerate();  // calls the Accelerate() method in the base class
  }

}


public class Example7_2
{

  public static void Main()
  {

    // create a Car object and call the object's Accelerate() method
    Car myCar = new Car("Toyota", "MR2");
    myCar.Accelerate();

    // create a Motorcycle object and call the object's Accelerate() method
    Motorcycle myMotorcycle = new Motorcycle("Harley-Davidson", "V-Rod");
    myMotorcycle.Accelerate();

  }

}