← Java from Scratch
Lesson 34 of 88 · 10 XP
Constructors
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A constructor is called by new; its name is the same as the class's, and it has no return type:
class Enemy {
String name;
int hp;
Enemy(String name, int hp) {
this.name = name;
this.hp = hp;
}
Enemy(String name) {
this(name, 100); // call another constructor — it must be the first line
}
}
- if there isn't a single constructor, the class has an empty "default" one; once you write your own, the empty one is gone,
and
new Enemy()won't compile; - a constructor guarantees that the object is in a correct state right away.
Task. Rectangle with the constructors (int w, int h) and (int side) (a square) and the methods area(),
perimeter(). The input is one or two numbers on a line; print <area> <perimeter>.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.