Polymorphism : Override Virtual « Class Interface « C# / C Sharp






Polymorphism

 


using System;

public class MotorVehicle {
    public string make;
    public string model;

    public MotorVehicle(string make, string model) {
        this.make = make;
        this.model = model;
    }

    public virtual void Accelerate() {
        Console.WriteLine(model + " accelerating");
    }

}
public class Product : MotorVehicle {
    public Product(string make, string model) :
        base(make, model) {
    }
    public override void Accelerate() {
        Console.WriteLine("Pushing gas pedal of " + model);
        base.Accelerate();
    }

}
public class Motorcycle : MotorVehicle {
    public Motorcycle(string make, string model) :
        base(make, model) {
        // do nothing
    }

    public override void Accelerate() {
        Console.WriteLine("Twisting throttle of " + model);
        base.Accelerate();
    }

}


class MainClass {

    public static void Main() {
        Product myProduct = new Product("Toyota", "MR2");
        myProduct.Accelerate();

        Motorcycle myMotorcycle =
          new Motorcycle("Harley-Davidson", "V-Rod");
        myMotorcycle.Accelerate();

    }

}

 








Related examples in the same category

1.Virtual keyword can be used to start a new inheritance ladder
2.Virtual and overloadVirtual and overload
3.Class hierarchy: override and virtual
4.Use virtual methods and polymorphismUse virtual methods and polymorphism
5.Demonstrate a virtual methodDemonstrate a virtual method
6.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
7.illustrates polymorphismillustrates polymorphism
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