2021 - Static
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;