illustrates polymorphism : Override Virtual « Class Interface « C# / C Sharp






illustrates polymorphism

illustrates polymorphism
/*
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();

  }

}


           
       








Related examples in the same category

1.Polymorphism
2.Virtual keyword can be used to start a new inheritance ladder
3.Virtual and overloadVirtual and overload
4.Class hierarchy: override and virtual
5.Use virtual methods and polymorphismUse virtual methods and polymorphism
6.Demonstrate a virtual methodDemonstrate a virtual method
7.When a virtual method is not overridden, the base class method is usedWhen a virtual method is not overridden, 
   the base class method is used
8.Demonstrates the use of a virtual method to override a base class methodDemonstrates the use of a virtual method to override a base class method
9.Demonstrates the use of a virtual property to override a base class propertyDemonstrates the use of a virtual property to override a base class property
10.Method override 3Method override 3
11.Test Polymorphism Virtual Functions