Abstract - Virtual - Static - 2017

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

Virtual

If a value is declared as virtual, a sub class can override the value.

For Example

The inspect method within the Animal class:

    public virtual void Inspect()
    {
      Console.Write("  ID " + ID + " ");
      Console.Write("Age " + Age + " ");
      Console.Write("LS " + NaturalLifespan + " ");
      Console.Write("Pr dth " + Math.Round(ProbabilityOfDeathOtherCauses, 2) + " ");
    }

The fox class overrides this:

    public override void Inspect()
    {
      base.Inspect();
      Console.Write("Food needed " + FoodUnitsNeeded + " ");
      Console.Write("Food eaten " + FoodUnitsConsumedThisPeriod + " ");
      Console.Write("Gender " + Gender + " ");
      Console.WriteLine();
    }

So does the rabbit class:

    public override void Inspect()
    {
      base.Inspect();
      Console.Write("Rep rate " + Math.Round(ReproductionRate, 1) + " ");
      Console.WriteLine("Gender " + Gender + " ");
    }

Static

Static is a more difficult to explain. The code below is from the Animal class:

class Animal
  {
    protected double NaturalLifespan;
    protected int ID;
    protected static int NextID = 1;
    protected int Age = 0;
    protected double ProbabilityOfDeathOtherCauses;
    protected bool IsAlive;
    protected static Random Rnd = new Random();

If we created an instance of the animal class and called it 'Monkey' we could access or set Monkey.ID, Monkey.Age etc.

However static values can't be altered by accessing the instance, so Monkey.NextID or Monkey.Rnd can't be accessed or changed.