Lesson 8 of 10
Classes and properties
- 14 min
- 6 checks
- 3 hints
- Go to task
Goal
Constructors, private set and encapsulation
Explanation
A class is a template, and an object is an instance made from it with its own data, as in var hero = new Player("Layan", 100);. new calls the constructor, a method with the same name as the class and no return type, whose job is to set up the new object. Everything in a class is private unless you say otherwise, so anything you want to use from outside the class needs public in front of it.
A public field public int Hp; lets any code write hero.Hp = 9999. A property public int Hp { get; private set; }, however, can be read from anywhere but changed only from inside the class, so every change goes through the class's methods, and those methods enforce the rules of the game: damage never takes health below zero, and healing never goes over the maximum. This is called encapsulation.
You write a computed property with an arrow, as in public bool IsAlive => Hp > 0;. It isn't stored: it's calculated from Hp every time you read it, so it always agrees with it.
Your task
Turn the fields Name, MaxHp and Hp in Player into { get; private set; } properties, and make the constructor store the name and the maximum health and start the player at full health. Then make IsAlive true as long as Hp is above zero, make TakeDamage(amount) lower Hp without taking it below zero, and make Heal(amount) raise it without going over MaxHp, but never heal a player who has fallen.
Checks
6 checks- The constructor stores the name and starts at full health
- TakeDamage lowers health
- Health never drops below zero, and IsAlive becomes false
- Heal raises health without going over MaxHp
- A player who has fallen can't be healed
- Name, MaxHp and Hp can be read from outside but not changed from there