Lesson 8 of 10

Classes and encapsulation

Goal

Private fields, the constructor and toString

01

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.

02

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
  1. The constructor stores the name and starts at full health
  2. takeDamage reduces health and never drops below zero
  3. heal raises health and never goes over the maximum
  4. isAlive returns true until health runs out
  5. toString returns text in the form Steve (HP 12/20)
  6. All fields are private
03

Hints

0/3
Track lessons0 of 10 done

Java is the language behind Android apps and large systems. Everything in it lives inside a class, and you state every variable's type explicitly.

Beginner level, 10 lessons, 2 hours in total.

Main.java
OutputJava 13 (Judge0)

Compiling and running your code on the server.

–/6

Compiling and running your code on the server.

6 checks listed under “Your task”.

Track lessons0 of 10 done

Java is the language behind Android apps and large systems. Everything in it lives inside a class, and you state every variable's type explicitly.

Beginner level, 10 lessons, 2 hours in total.