WHAT YOU WILL MAKE
Make three kinds of entrance player generators
Can write a constructor with the same name as the class; can use this to distinguish fields and parameters; can complete verification when the object is born; can use constructor overloading to provide three legal birth methods. Prerequisites: classes, fields, instance methods, parameters, overloads and object references. Today, every object must be in a legal state from the first second of birth.
Before you start: It is recommended to complete Lessons 17–18 first
- Default bornthis("Steve")
- Specify namethis(name, 20)
- Complete constructorVerify and write fields
01 / 12
Before you begin: Put the examples in the right place
This chapter uses JDK 21 and does not require the preview function. A complete program is given for each common example, saved with annotated file names. Multiple examples are placed in their own folders to avoid auxiliary classes with the same name.
Terminal command: Replace the Chinese placeholder with the actual name
javac -encoding UTF-8 ExampleFile.java
java ExampleClassClass names are case-sensitive. If the complete challenge code is divided into multiple sections, please connect them in the same file in order. Do not create separate classes for the continued sections. Run verification only lists the program output; additional input sequences are provided where input is required.
02 / 12
constructor is responsible for birth physical examination
If you write new first and then write fields one by one, it is easy to miss names or leave negative lives. The constructor puts the necessary data into the creation process.
- newSelect matching constructor
- ConstructorInitialize new object
- FieldSave birth status
- AuthenticationEnsure legality when creation is completed
L19Example01.java · Complete independent example
class Player {
String name;
int health;
Player(String name, int health) {
this.name = name == null || name.isBlank() ? "Steve" : name.trim();
this.health = Math.max(1, Math.min(20, health));
}
Player(String name) { this(name, 20); }
Player() { this("Steve"); }
}
public class L19Example01 {
public static void main(String[] args) {
Player alex = new Player("Alex", 20);
System.out.println(alex.name + "," + alex.health);
}
}Output
Alex,2003 / 12
Constructor syntax map
The constructor is written in the class body. The actual parameters after new must match a constructor parameter list.
- Class nameThe constructor must have the same name
- Parameter listMust match actual parameters
- Return typeConstructor has no return type
- No parametersAfter explicitly declaring the constructor, no parameters will be automatically filled.
L19Example02.java · Complete independent example
class Mob {
String name; int health;
Mob(String name, int health) {
this.name = name; this.health = health;
}
}
public class L19Example02 {
public static void main(String[] args) {
Mob zombie = new Mob("Small stiffness", 20);
System.out.println(zombie.name);
}
}Output
Small stiffness04 / 12
this points to the current object
Constructors often make parameter names consistent with field names. At this time, the short name represents the parameter, and the this. field represents the object field being created.
- this.nameCurrent object field
- nameThe parameters passed in this time
- Correct assignmentField receives parameter value
- name=nameThe parameters are assigned to itself, and the fields remain unchanged.
L19Example03.java · Complete independent example
class Player {
String name;
Player(String name) { name = name; }
}
public class L19Example03 {
public static void main(String[] args) {
Player p = new Player("Alex");
System.out.println(p.name);
}
}Output
null05 / 12
Complete verification at birth
The constructor is the first door to keep the legal state of the object. Define the rules first, then choose to modify values or throw exceptions. Safe defaults can be used during the initial learning phase.
- Bad nameReplaced by Steve
- Valid nameRemove blanks at both ends
- LifeCorrected to 1 to 20
- StrategyAll entrances remain consistent
L19Example04.java · Complete independent example
class Player {
String name;
int health;
Player(String name, int health) {
this.name = name == null || name.isBlank() ? "Steve" : name.trim();
this.health = Math.max(1, Math.min(20, health));
}
Player(String name) { this(name, 20); }
Player() { this("Steve"); }
}
public class L19Example04 {
public static void main(String[] args) {
Player p = new Player("", -8);
System.out.println(p.name + "," + p.health);
}
}Output
Steve,106 / 12
Constructor overloading
The constructor can be overloaded to provide a concise entry for common creation methods. Parameter lists must be different.
- Player()Provide default name
- Player(name)Provide default life
- Complete constructorWrite field after verification
L19Example05.java · Complete independent example
class Player {
String name;
int health;
Player(String name, int health) {
this.name = name == null || name.isBlank() ? "Steve" : name.trim();
this.health = Math.max(1, Math.min(20, health));
}
Player(String name) { this(name, 20); }
Player() { this("Steve"); }
}
public class L19Example05 {
public static void main(String[] args) {
Player a = new Player("Alex", 12);
Player b = new Player("Builder");
Player c = new Player();
System.out.println(a.name + "," + a.health);
System.out.println(b.name + "," + b.health);
System.out.println(c.name + "," + c.health);
}
}Output
Alex,12
Builder,20
Steve,2007 / 12
this constructor chain
this(...) calls another constructor of this class, which must be the first statement of the constructor. In this way, only one copy of the default value and verification is maintained.
- Player()Provide default name
- Player(name)Provide default life
- Complete constructorWrite field after verification
BadConstructorOrder.java · Intentional error example
class Player {
Player(String name) { }
Player() {
System.out.println("Birth");
this("Steve");
}
}
public class BadConstructorOrder {
public static void main(String[] args) { }
}08 / 12
Legal status and testing
The rules that are expected to be maintained in the design are called invariant conditions. This lesson first ensures that when the Player is first created, its name cannot be empty, and its life must be between 1 and 20 when it is born.
- NameNot empty after creation
- Life1 to 20 at birth
- coordinatesWithin project -100 to 100
- Long-term guaranteeIt is also necessary to encapsulate to prevent arbitrary modifications
| Test | Creation method | Expected |
|---|---|---|
| Complete | new Player("Alex", 12) | Alex 12 |
| Default life | new Player("Alex") | Alex 20 |
| Full default | new Player() | Steve 20 |
| Bad name | new Player("", 8) | Steve 8 |
| Bad life | new Player("Alex", 99) | Alex 20 |
09 / 12
Constructor Failure Clinic
When reading "constructor cannot be applied", compare the actual parameter quantity and type of new, and then check the constructor declaration.
- void class nameOrdinary method, not constructor
- Multiple actual parametersNo matching entry
- this orderThe first sentence is required in Java21
- Missing fieldMay leave default value
BadConstructorCall.java · Intentional error example
class Player {
Player(String name) { }
}
public class BadConstructorCall {
public static void main(String[] args) {
Player p = new Player("Alex", 20, 3);
}
}L19Example08B.java · Complete independent example
class Player {
String name;
void Player(String name) { this.name = name; }
}
public class L19Example08B {
public static void main(String[] args) {
Player p = new Player();
System.out.println(p.name);
}
}Output
null10 / 12
Challenge Realization Three Legal Births
The challenge program is called PlayerSpawn. The three constructors support complete birth, specified name and complete default respectively.
- Complete playerName, life and coordinates
- Specify nameThe rest use default values
- Default playerSteve and the default state
- Bad materialModify according to unified strategy
PlayerSpawn.java · Complete standalone example
public class PlayerSpawn {
static class Player {
String name;
int health;
int x;
int z;
Player(String name, int health, int x, int z) {
this.name = name == null || name.isBlank() ? "Steve" : name.trim();
this.health = Math.max(1, Math.min(20, health));
this.x = Math.max(-100, Math.min(100, x));
this.z = Math.max(-100, Math.min(100, z));
}
Player(String name) {
this(name, 20, 0, 0);
}
Player() {
this("Steve");
}
void describe() {
System.out.println(name + " Life=" + health
+ " Birth point=(" + x + "," + z + ")");
}
}
public static void main(String[] args) {
Player a = new Player("Alex", 18, 12, -7);
Player b = new Player("Builder");
Player c = new Player();
Player d = new Player("", -5, 999, -999);
a.describe(); b.describe(); c.describe(); d.describe();
}
}Output
Alex Life=18 Birth point=(12,-7)
Builder Life=20 Birth point=(0,0)
Steve Life=20 Birth point=(0,0)
Steve Life=1 Birth point=(100,-100)11 / 12
Expansion tasks and clearance review
The assignment requires writing at least two tests for each constructor and stating the invariant conditions of the object.
- Wooden PickaxeMob adds constructor
- Iron PickaxeOverloading and Life Boundary
- Diamond PickaxeLimit random birth area
- ReviewBirth rules and this
Third gear operation
- Wooden Pickaxe: Add a constructor to Lesson 17 Mob, and a name and life must be provided when creating it.
- Iron Pickaxe: Add overloaded constructor and parameter verification, keep life from 0 to 20.
- Diamond Pickaxe: Designed with random birth coordinates, but guaranteed not to fall within the designated danger range.
| Self-evaluation | Can | Still need to practice |
|---|---|---|
| I can identify constructors | □ | □ |
| I would use this | □ | □ |
| I will test the birth rules | □ | □ |
12 / 12
Own acceptance record
Write expectations before running, and record actual results after running. Normal cases show that the program does things; edge cases show that it knows when to stop; error cases show that it rejects unreasonable requests.
| Category | Input of your choice | Expectation and actual |
|---|---|---|
| Normal | A common value or a successful operation | Is it consistent line by line? |
| Border | Minimum value, maximum value and adjacent value | Is there one less square and one more step? |
| Error | Illegal quantity, missing object or incorrect syntax | Explicitly reject? Is the status maintained? |
- Write a bug as: triggering conditions, phenomena, causes, and minimal repairs.
- Organize a rule worth remembering and explain it in your own words. Don't just copy the definition.
- Change an example, keep a record of the test, and let the results prove your understanding.
TAKE IT WITH YOU
Take the lesson offline
The complete lesson, code, diagrams and exercises, in your preferred language.