2021 - Constructors

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

What is a Constructor?

When a class is used to Instantiate (create) an object, the constructor will be the first block of code to be run. This is used to setup the object.

The constructor can also have parameters, these will need to be passed whenever an object is instantiated (created).

Each of the classes within the skeleton program have a constructor.

How can you identify the Constructor?

The constructor method must use the exact same name as the class. So for example in the 'Piece' class the contructor is a method called 'Piece'.

The code below is the start of the 'Piece' class:

class Piece
    {
        protected bool destroyed, belongsToPlayer1;
        protected int fuelCostOfMove, VPValue, connectionsToDestroy;
        protected string pieceType;

        public Piece(bool player1)
        {
            fuelCostOfMove = 1;
            belongsToPlayer1 = player1;
            destroyed = false;
            pieceType = "S";
            VPValue = 1;
            connectionsToDestroy = 2;
        }
     }

What can a constructor do?

The constructor is used to set the starting variables for the object created, for example the constructor will set the default values. The constructor will also process the parameter's passed into the constructor and store them if required. This can be seen in the code above.