Encapsulation
Encapsulation is the practice of grouping variables and methods inside a class in a way that restricts direct access to some components of an object. It is used to prevent accidental interference and misuse of the methods and data.
For example:
public class PlayerWallet
{
private int coins;
public PlayerWallet(int initialBalance)
{
coins = initialBalance;
}
public int GetBalance()
{
return coins;
}
public void Deposit(int amount)
{
if (amount > 0)
{
coins += amount;
}
}
public bool Withdraw(int amount)
{
if (amount <= 0 || amount > coins)
{
return false;
}
coins -= amount;
return true;
}
}
In this case the value coins
is encapsulated in a few different public methods that modify the value. This allows for you to interact with it without risk of you performing an invalid operation.