Survival Game Example
Here is an example of getters and setters in the context of a hypothetical survival computer game:
In this example, we have a base Character
class that represents any character in the game with a name, health, and max health. The Player
class extends the Character
class and adds an inventory
property. We have defined getters and setters for all of these properties, allowing us to control how they are accessed and modified. The heal
and damage
methods use the setter for the health
property to ensure that the character's health never exceeds their max health. The Player
class also has a useItem
method for using items from their inventory.
Last updated