← Java from Scratch
Lesson 31 of 88 · 10 XP
Class attributes
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Attributes (fields) get default values: 0, 0.0, false, null — unlike local variables.
class Enemy {
String name; // each object has its own
int hp = 100; // an initial value
final int id; // final — can be set exactly once (in the constructor)
static int created = 0; // static — ONE for the whole class, shared by all objects
Enemy(String name) {
this.name = name;
created++;
id = created;
}
}
new Enemy("Orc"); new Enemy("Goblin");
System.out.println(Enemy.created); // 2 — static members are accessed through the class name
Task. Finish the class Ticket: each ticket has its own number final int number (1, 2, 3… in the order
they're created) and the owner's name; the shared counter is static int issued. The program creates tickets from the input lines,
prints them, and at the end prints total: N.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.