Difference between revisions of "2021 - Static"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(How is it used?)
(How is it used?)
Line 64: Line 64:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Static methods are not available within the objects of a class.
+
Static methods are not available within the objects of a class. Instead you will have to use:
 +
 
 +
 
 +
<syntaxhighlight lang=c#>
 +
 
 +
PBDSPiece.rNoGen;
 +
 
 +
</syntaxhighlight>

Revision as of 10:23, 24 September 2020

What is Static?

Within OOP programming, Static is a method which can be called without creating an object of the class.

Where is it used?

This can be seen in the 'PBDSPiece' class:

    class PBDSPiece : Piece
    {
        static Random rNoGen = new Random();

        public PBDSPiece(bool player1)
            : base(player1)
        {
            pieceType = "P";
            VPValue = 2;
            fuelCostOfMove = 2;
        }

        public override int CheckMoveIsValid(int distanceBetweenTiles, string startTerrain, string endTerrain)
        {
            if (distanceBetweenTiles != 1 || startTerrain == "~")
            {
                return -1;
            }
            return fuelCostOfMove;
        }

        public int Dig(string terrain)
        {
            if (terrain != "~")
            {
                return 0;
            }
            if (rNoGen.NextDouble() < 0.9)
            {
                return 1;
            }
            else
            {
                return 5;
            }
        }
    }

'rNoGen' is declared as static.

How is it used?

If we created a new 'PBDSPiece':

PBDSPiece piece = new PBDSPiece(true);

You would not be able to use:

piece.rNoGen;

Static methods are not available within the objects of a class. Instead you will have to use:


PBDSPiece.rNoGen;