← Java tutorials

LESSON 19 / 40 · FREE TUTORIAL

Spawn Points and Constructors

Constructor this and initialization

90–110 minutesThis chapter uses JDK 21 and does not require the preview function.Object-oriented Introduction

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

Three entrances, one initialization route
  1. Default bornthis("Steve")
  2. Specify namethis(name, 20)
  3. 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 ExampleClass

Class 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.

new calls the constructor to create and initialize the object
  1. newSelect matching constructor
  2. ConstructorInitialize new object
  3. FieldSave birth status
  4. 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,20

03 / 12

Constructor syntax map

The constructor is written in the class body. The actual parameters after new must match a constructor parameter list.

Class name, parameters and constructor body are indispensable.
  1. Class nameThe constructor must have the same name
  2. Parameter listMust match actual parameters
  3. Return typeConstructor has no return type
  4. 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 stiffness

04 / 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.

When the parameter name covers the field name, this opens the object box
  1. this.nameCurrent object field
  2. nameThe parameters passed in this time
  3. Correct assignmentField receives parameter value
  4. 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

null

05 / 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.

Illegal material is corrected or rejected at constructor entry
  1. Bad nameReplaced by Steve
  2. Valid nameRemove blanks at both ends
  3. LifeCorrected to 1 to 20
  4. 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,1

06 / 12

Constructor overloading

The constructor can be overloaded to provide a concise entry for common creation methods. Parameter lists must be different.

Constructor delegation: only one copy of the verification is retained in the end
  1. Player()Provide default name
  2. Player(name)Provide default life
  3. 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,20

07 / 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.

Constructor delegation: only one copy of the verification is retained in the end
  1. Player()Provide default name
  2. Player(name)Provide default life
  3. 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.

Objects should satisfy indestructible rules as soon as they are born
  1. NameNot empty after creation
  2. Life1 to 20 at birth
  3. coordinatesWithin project -100 to 100
  4. Long-term guaranteeIt is also necessary to encapsulate to prevent arbitrary modifications
Acceptance and inspection forms
TestCreation methodExpected
Completenew Player("Alex", 12)Alex 12
Default lifenew Player("Alex")Alex 20
Full defaultnew Player()Steve 20
Bad namenew Player("", 8)Steve 8
Bad lifenew 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.

Compilation errors usually come from name parameters or this order
  1. void class nameOrdinary method, not constructor
  2. Multiple actual parametersNo matching entry
  3. this orderThe first sentence is required in Java21
  4. 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

null

10 / 12

Challenge Realization Three Legal Births

The challenge program is called PlayerSpawn. The three constructors support complete birth, specified name and complete default respectively.

The constructor chain sends all birth modes into the same set of checks
  1. Complete playerName, life and coordinates
  2. Specify nameThe rest use default values
  3. Default playerSteve and the default state
  4. 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.

Third gear task expansion generation point
  1. Wooden PickaxeMob adds constructor
  2. Iron PickaxeOverloading and Life Boundary
  3. Diamond PickaxeLimit random birth area
  4. 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.
Acceptance and inspection forms
Self-evaluationCanStill 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.

Write the evidence into the record
CategoryInput of your choiceExpectation and actual
NormalA common value or a successful operationIs it consistent line by line?
BorderMinimum value, maximum value and adjacent valueIs there one less square and one more step?
ErrorIllegal quantity, missing object or incorrect syntaxExplicitly 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.