Constructors - 2017

From TRCCompSci - AQA Computer Science
Revision as of 05:24, 26 May 2017 by Admin (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
  • A constructor method has the same name as the class.
  • It is used when an instance of the class is created, the constructor method will always be run.
  • A class can have many constructor methods.

Example

class Warren
  {
    private const int MaxRabbitsInWarren = 99;
    private Rabbit[] Rabbits;
    private int RabbitCount = 0;
    private int PeriodsRun = 0;
    private bool AlreadySpread = false;
    private int Variability;
    private static Random Rnd = new Random();

    public Warren(int Variability)
    {
      this.Variability = Variability;
      Rabbits = new Rabbit[MaxRabbitsInWarren];
      RabbitCount = (int)(CalculateRandomValue((int)(MaxRabbitsInWarren / 4), this.Variability));
      for (int r = 0; r < RabbitCount; r++)
      {
        Rabbits[r] = new Rabbit(Variability);
      }
    }

    public Warren(int Variability, int rabbitCount)
    {
      this.Variability = Variability;
      this.RabbitCount = rabbitCount;
      Rabbits = new Rabbit[MaxRabbitsInWarren];
      for (int r = 0; r < RabbitCount; r++)
      {
        Rabbits[r] = new Rabbit(Variability);
      }
    }

This is from the Warren class, as you can see the name of the class has been used as a method (This is therefore a constructor). Two constructors have been declared, one that accepts just one parameter and that accepts two parameters.