Difference between revisions of "2021 - Static"
(→What is Static?) |
(→How is it used?) |
||
Line 55: | Line 55: | ||
PBDSPiece piece = new PBDSPiece(true); | PBDSPiece piece = new PBDSPiece(true); | ||
− | </ | + | </syntaxhighlight> |
You would not be able to use: | You would not be able to use: | ||
Line 62: | Line 62: | ||
piece.rNoGen; | piece.rNoGen; | ||
− | </ | + | </syntaxhighlight> |
Static methods are not available within the objects of a class. | Static methods are not available within the objects of a class. |
Revision as of 10:22, 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.