Lesson 8 of 10
Classes and encapsulation
- 14 min
- 6 checks
- 3 hints
- Go to task
Goal
Private fields, the constructor and toString
Explanation
A class is a template you create objects from. Each object keeps its data in fields and its behavior in methods. The methods here are written without static, because they work on a specific object and can read its fields. new Player("Steve", 20) creates a new object and calls the constructor, which has the same name as the class, has no return type, and has one job: giving the fields their starting values. this.name = name tells the object's field apart from the parameter with the same name.
Encapsulation means making the fields private so no code outside the class can reach them, and routing every change through public methods that enforce the rules. If hp were exposed, any code could write steve.hp = -50, but when every change goes through takeDamage, health can never drop below zero. The small methods that read fields are called getters, like getHp().
When you write println(steve), toString() gets called, and if you haven't defined it, you get something like Player@1b6d3586. So define it with @Override public String toString(). The @Override annotation asks the compiler to make sure you're overriding a method that actually exists, so it catches a typo in the name like tostring.
Your task
Make the fields of Player private, complete the constructor Player(name, maxHp) so health starts full, then complete getName() and getHp(). Make takeDamage(amount) reduce health without dropping below zero, heal(amount) raise it without going over maxHp, and isAlive() return true as long as health is above zero. Then define toString() to return text like Steve (HP 12/20).
Checks
6 checks- The constructor stores the name and starts at full health
- takeDamage reduces health and never drops below zero
- heal raises health and never goes over the maximum
- isAlive returns true until health runs out
- toString returns text in the form Steve (HP 12/20)
- All fields are private