Creating a Person object shouldn't require separate calls to set name and age. Constructors let you initialize an object in one step: new Person("Alice", 30) creates a fully-formed object immediately.

Default constructor

The constructor Java provides when you don't write one.

DefaultConstructor.java
Replay: real traced execution (multi-file project)
public class DefaultConstructor {
    public static void main(String[] args) {
        System.out.println("=== Default Constructor ===\n");

        // Java provides default constructor when you write none
        SimpleClass obj = new SimpleClass();

        System.out.println("Object created with default constructor");
        System.out.println("number: " + obj.number);  // Default: 0
        System.out.println("text: " + obj.text);      // Default: null
        System.out.println("flag: " + obj.flag);      // Default: false

        // We can still set fields after construction
        obj.number = 42;
        obj.text = "Hello";
        obj.flag = true;

        System.out.println("\nAfter setting values:");
        System.out.println("number: " + obj.number);
        System.out.println("text: " + obj.text);
        System.out.println("flag: " + obj.flag);

        System.out.println("\n=== No Default If You Write One ===");
        // WithConstructor obj2 = new WithConstructor();  // Error!
        WithConstructor obj2 = new WithConstructor("Required");
        System.out.println("value: " + obj2.value);
    }
}

// Class without explicit constructor
class SimpleClass {
    int number;
    String text;
    boolean flag;

    // Java adds this automatically:
    // SimpleClass() { }
}

// Class with explicit constructor
class WithConstructor {
    String value;

    WithConstructor(String v) {  // No default constructor now!
        value = v;
    }
}
  1. obj ← ⟨SimpleClass A⟩, obj.number ← 42, obj.text ← Hello, obj.flag ← true

    1public class DefaultConstructor {2    public static void main(String[] args) {3        System.out.println("=== Default Constructor ===\n");4        5        // Java provides default constructor when you write none  //?default6        SimpleClass obj→ ⟨SimpleClass A⟩ = new SimpleClass();7        8        System.out.println("Object created with default constructor");9        System.out.println("number: " + obj.number0);  // Default: 010        System.out.println("text: " + obj.textnull);      // Default: null11        System.out.println("flag: " + obj.flagfalse);      // Default: false12        13        // We can still set fields after construction  //?setafter14        obj.number→ 42 = 42;15        obj.text→ Hello = "Hello";16        obj.flag→ true = true;17        18        System.out.println("\nAfter setting values:");19        System.out.println("number: " + obj.number42);20        System.out.println("text: " + obj.textHello);21        System.out.println("flag: " + obj.flagtrue);22        23        System.out.println("\n=== No Default If You Write One ===");  //?nodefault24        // WithConstructor obj2 = new WithConstructor();  // Error!25        WithConstructor obj2 = new WithConstructor("Required");26        System.out.println("value: " + obj2.value);
    output=== Default Constructor ===
    Object created with default constructor
    number: 0
    text: null
    flag: false
    
    After setting values:
    number: 42
    text: Hello
    flag: true
    
    === No Default If You Write One ===
  2. value ← Required, obj2 ← ⟨WithConstructor B⟩

    24        // WithConstructor obj2 = new WithConstructor();  // Error!25        WithConstructor obj2→ ⟨WithConstructor B⟩ = new WithConstructor("Required");26        System.out.println("value: " + obj2.valueRequired);27    }28}2930// Class without explicit constructor  //?simpleclass31class SimpleClass {32    int number;33    String text;34    boolean flag;35    36    // Java adds this automatically:37    // SimpleClass() { }38}3940// Class with explicit constructor  //?withctr41class WithConstructor {42    String value;43    44    WithConstructor(String vRequired) {  // No default constructor now!45        value→ Required = vRequired;46    }
    outputvalue: Required

No-arg constructor sets fields to defaults: 0, null, false.

default constructor Java provides one if you write no constructors. Takes no parameters.

Parameterized constructor

Accept values to initialize fields.

example
ParameterizedConstructor.java
Replay: real traced execution (multi-file project)
public class ParameterizedConstructor {
    public static void main(String[] args) {
        System.out.println("=== Parameterized Constructor ===\n");

        // Create Person with required data
        int firstAge = 30;
        String secondName = "Bob";
        Person alice = new Person("Alice", firstAge);
        Person bob = new Person(secondName, 25);

        System.out.println("Created: " + alice.describe());
        System.out.println("Created: " + bob.describe());

        // No way to create incomplete Person!
        // Person invalid = new Person();  // Won't compile

        System.out.println("\n=== Benefits ===");
        System.out.println("✓ Object is fully initialized immediately");
        System.out.println("✓ Can't forget to set required fields");
        System.out.println("✓ Clear what data is needed");
    }
}

class Person {
    String name;
    int age;

    // Parameterized constructor
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    String describe() {
        return name + " (age " + age + ")";
    }
}
public class ParameterizedConstructor {
    public static void main(String[] args) {
        System.out.println("=== Parameterized Constructor ===\n");

        // Create Person with required data
        int firstAge = 22;
        String secondName = "Bob";
        Person alice = new Person("Alice", firstAge);
        Person bob = new Person(secondName, 25);

        System.out.println("Created: " + alice.describe());
        System.out.println("Created: " + bob.describe());

        // No way to create incomplete Person!
        // Person invalid = new Person();  // Won't compile

        System.out.println("\n=== Benefits ===");
        System.out.println("✓ Object is fully initialized immediately");
        System.out.println("✓ Can't forget to set required fields");
        System.out.println("✓ Clear what data is needed");
    }
}

class Person {
    String name;
    int age;

    // Parameterized constructor
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    String describe() {
        return name + " (age " + age + ")";
    }
}
public class ParameterizedConstructor {
    public static void main(String[] args) {
        System.out.println("=== Parameterized Constructor ===\n");

        // Create Person with required data
        int firstAge = 45;
        String secondName = "Bob";
        Person alice = new Person("Alice", firstAge);
        Person bob = new Person(secondName, 25);

        System.out.println("Created: " + alice.describe());
        System.out.println("Created: " + bob.describe());

        // No way to create incomplete Person!
        // Person invalid = new Person();  // Won't compile

        System.out.println("\n=== Benefits ===");
        System.out.println("✓ Object is fully initialized immediately");
        System.out.println("✓ Can't forget to set required fields");
        System.out.println("✓ Clear what data is needed");
    }
}

class Person {
    String name;
    int age;

    // Parameterized constructor
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    String describe() {
        return name + " (age " + age + ")";
    }
}
public class ParameterizedConstructor {
    public static void main(String[] args) {
        System.out.println("=== Parameterized Constructor ===\n");

        // Create Person with required data
        int firstAge = 30;
        String secondName = "Kai";
        Person alice = new Person("Alice", firstAge);
        Person bob = new Person(secondName, 25);

        System.out.println("Created: " + alice.describe());
        System.out.println("Created: " + bob.describe());

        // No way to create incomplete Person!
        // Person invalid = new Person();  // Won't compile

        System.out.println("\n=== Benefits ===");
        System.out.println("✓ Object is fully initialized immediately");
        System.out.println("✓ Can't forget to set required fields");
        System.out.println("✓ Clear what data is needed");
    }
}

class Person {
    String name;
    int age;

    // Parameterized constructor
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    String describe() {
        return name + " (age " + age + ")";
    }
}
public class ParameterizedConstructor {
    public static void main(String[] args) {
        System.out.println("=== Parameterized Constructor ===\n");

        // Create Person with required data
        int firstAge = 30;
        String secondName = "Mina";
        Person alice = new Person("Alice", firstAge);
        Person bob = new Person(secondName, 25);

        System.out.println("Created: " + alice.describe());
        System.out.println("Created: " + bob.describe());

        // No way to create incomplete Person!
        // Person invalid = new Person();  // Won't compile

        System.out.println("\n=== Benefits ===");
        System.out.println("✓ Object is fully initialized immediately");
        System.out.println("✓ Can't forget to set required fields");
        System.out.println("✓ Clear what data is needed");
    }
}

class Person {
    String name;
    int age;

    // Parameterized constructor
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    String describe() {
        return name + " (age " + age + ")";
    }
}
  1. firstAge ← 30, secondName ← Bob

    1public class ParameterizedConstructor {2    public static void main(String[] args) {3        System.out.println("=== Parameterized Constructor ===\n");4        5        // Create Person with required data  //?create6        int firstAge→ 30 = 30;  //@firstAge=22, 457        String secondName→ Bob = "Bob";  //@secondName="Kai", "Mina"8        Person alice = new Person("Alice", firstAge);9        Person bob = new Person(secondName, 25);
    output=== Parameterized Constructor ===
  2. this.name ← Alice, this.age ← 30, alice ← ⟨Person A⟩

    pass 1 of 2
    7        String secondName = "Bob";  //@secondName="Kai", "Mina"8        Person alice→ ⟨Person A⟩ = new Person("Alice", firstAge);9        Person bob = new Person(secondName, 25);10        11        System.out.println("Created: " + alice.describe());12        System.out.println("Created: " + bob.describe());13        14        // No way to create incomplete Person!  //?noinvalid15        // Person invalid = new Person();  // Won't compile16        17        System.out.println("\n=== Benefits ===");18        System.out.println("✓ Object is fully initialized immediately");19        System.out.println("✓ Can't forget to set required fields");20        System.out.println("✓ Clear what data is needed");21    }22}2324class Person {25    String name;  //?fields26    int age;27    28    // Parameterized constructor  //?constructor29    Person(String nameAlice, int age30) {30        this.name→ Alice = nameAlice;  //?this31        this.age→ 30 = age30;32    }
  3. this.name ← Bob, this.age ← 25, bob ← ⟨Person B⟩

    pass 2 of 2
    8        Person alice = new Person("Alice", firstAge);9        Person bob→ ⟨Person B⟩ = new Person(secondName, 25);10        11        System.out.println("Created: " + alice.describe());12        System.out.println("Created: " + bob.describe());13        14        // No way to create incomplete Person!  //?noinvalid15        // Person invalid = new Person();  // Won't compile16        17        System.out.println("\n=== Benefits ===");18        System.out.println("✓ Object is fully initialized immediately");19        System.out.println("✓ Can't forget to set required fields");20        System.out.println("✓ Clear what data is needed");21    }22}2324class Person {25    String name;  //?fields26    int age;27    28    // Parameterized constructor  //?constructor29    Person(String nameBob, int age25) {30        this.name→ Bob = nameBob;  //?this31        this.age→ 25 = age25;32    }
  4. String describe()

    pass 1 of 2
    34String describe() {35    return nameAlice + " (age " + age30 + ")";36}
  5. System.out.println("Created: " + alice.describe());

    11System.out.println("Created: " + alice.describe());12System.out.println("Created: " + bob.describe());
    outputCreated: Alice (age 30)
  6. String describe()

    pass 2 of 2
    34String describe() {35    return nameBob + " (age " + age25 + ")";36}
  7. System.out.println("Created: " + bob.describe());

    11    System.out.println("Created: " + alice.describe());12    System.out.println("Created: " + bob.describe());13    14    // No way to create incomplete Person!  //?noinvalid15    // Person invalid = new Person();  // Won't compile16    17    System.out.println("\n=== Benefits ===");18    System.out.println("✓ Object is fully initialized immediately");19    System.out.println("✓ Can't forget to set required fields");20    System.out.println("✓ Clear what data is needed");21}
    outputCreated: Bob (age 25)
    
    === Benefits ===
    ✓ Object is fully initialized immediately
    ✓ Can't forget to set required fields
    ✓ Clear what data is needed
  1. firstAge ← 22, secondName ← Bob

    1public class ParameterizedConstructor {2    public static void main(String[] args) {3        System.out.println("=== Parameterized Constructor ===\n");4        5        // Create Person with required data6        int firstAge→ 22 = 22;7        String secondName→ Bob = "Bob";8        Person alice = new Person("Alice", firstAge);9        Person bob = new Person(secondName, 25);
    output=== Parameterized Constructor ===
  2. this.name ← Alice, this.age ← 22, alice ← ⟨Person A⟩

    pass 1 of 2
    7        String secondName = "Bob";8        Person alice→ ⟨Person A⟩ = new Person("Alice", firstAge);9        Person bob = new Person(secondName, 25);10        11        System.out.println("Created: " + alice.describe());12        System.out.println("Created: " + bob.describe());13        14        // No way to create incomplete Person!15        // Person invalid = new Person();  // Won't compile16        17        System.out.println("\n=== Benefits ===");18        System.out.println("✓ Object is fully initialized immediately");19        System.out.println("✓ Can't forget to set required fields");20        System.out.println("✓ Clear what data is needed");21    }22}2324class Person {25    String name;26    int age;27    28    // Parameterized constructor29    Person(String nameAlice, int age22) {30        this.name→ Alice = nameAlice;31        this.age→ 22 = age22;32    }
  3. this.name ← Bob, this.age ← 25, bob ← ⟨Person B⟩

    pass 2 of 2
    8        Person alice = new Person("Alice", firstAge);9        Person bob→ ⟨Person B⟩ = new Person(secondName, 25);10        11        System.out.println("Created: " + alice.describe());12        System.out.println("Created: " + bob.describe());13        14        // No way to create incomplete Person!15        // Person invalid = new Person();  // Won't compile16        17        System.out.println("\n=== Benefits ===");18        System.out.println("✓ Object is fully initialized immediately");19        System.out.println("✓ Can't forget to set required fields");20        System.out.println("✓ Clear what data is needed");21    }22}2324class Person {25    String name;26    int age;27    28    // Parameterized constructor29    Person(String nameBob, int age25) {30        this.name→ Bob = nameBob;31        this.age→ 25 = age25;32    }
  4. String describe()

    pass 1 of 2
    34String describe() {35    return nameAlice + " (age " + age22 + ")";36}
  5. System.out.println("Created: " + alice.describe());

    11System.out.println("Created: " + alice.describe());12System.out.println("Created: " + bob.describe());
    outputCreated: Alice (age 22)
  6. String describe()

    pass 2 of 2
    34String describe() {35    return nameBob + " (age " + age25 + ")";36}
  7. System.out.println("Created: " + bob.describe());

    11    System.out.println("Created: " + alice.describe());12    System.out.println("Created: " + bob.describe());13    14    // No way to create incomplete Person!15    // Person invalid = new Person();  // Won't compile16    17    System.out.println("\n=== Benefits ===");18    System.out.println("✓ Object is fully initialized immediately");19    System.out.println("✓ Can't forget to set required fields");20    System.out.println("✓ Clear what data is needed");21}
    outputCreated: Bob (age 25)
    
    === Benefits ===
    ✓ Object is fully initialized immediately
    ✓ Can't forget to set required fields
    ✓ Clear what data is needed
  1. firstAge ← 45, secondName ← Bob

    1public class ParameterizedConstructor {2    public static void main(String[] args) {3        System.out.println("=== Parameterized Constructor ===\n");4        5        // Create Person with required data6        int firstAge→ 45 = 45;7        String secondName→ Bob = "Bob";8        Person alice = new Person("Alice", firstAge);9        Person bob = new Person(secondName, 25);
    output=== Parameterized Constructor ===
  2. this.name ← Alice, this.age ← 45, alice ← ⟨Person A⟩

    pass 1 of 2
    7        String secondName = "Bob";8        Person alice→ ⟨Person A⟩ = new Person("Alice", firstAge);9        Person bob = new Person(secondName, 25);10        11        System.out.println("Created: " + alice.describe());12        System.out.println("Created: " + bob.describe());13        14        // No way to create incomplete Person!15        // Person invalid = new Person();  // Won't compile16        17        System.out.println("\n=== Benefits ===");18        System.out.println("✓ Object is fully initialized immediately");19        System.out.println("✓ Can't forget to set required fields");20        System.out.println("✓ Clear what data is needed");21    }22}2324class Person {25    String name;26    int age;27    28    // Parameterized constructor29    Person(String nameAlice, int age45) {30        this.name→ Alice = nameAlice;31        this.age→ 45 = age45;32    }
  3. this.name ← Bob, this.age ← 25, bob ← ⟨Person B⟩

    pass 2 of 2
    8        Person alice = new Person("Alice", firstAge);9        Person bob→ ⟨Person B⟩ = new Person(secondName, 25);10        11        System.out.println("Created: " + alice.describe());12        System.out.println("Created: " + bob.describe());13        14        // No way to create incomplete Person!15        // Person invalid = new Person();  // Won't compile16        17        System.out.println("\n=== Benefits ===");18        System.out.println("✓ Object is fully initialized immediately");19        System.out.println("✓ Can't forget to set required fields");20        System.out.println("✓ Clear what data is needed");21    }22}2324class Person {25    String name;26    int age;27    28    // Parameterized constructor29    Person(String nameBob, int age25) {30        this.name→ Bob = nameBob;31        this.age→ 25 = age25;32    }
  4. String describe()

    pass 1 of 2
    34String describe() {35    return nameAlice + " (age " + age45 + ")";36}
  5. System.out.println("Created: " + alice.describe());

    11System.out.println("Created: " + alice.describe());12System.out.println("Created: " + bob.describe());
    outputCreated: Alice (age 45)
  6. String describe()

    pass 2 of 2
    34String describe() {35    return nameBob + " (age " + age25 + ")";36}
  7. System.out.println("Created: " + bob.describe());

    11    System.out.println("Created: " + alice.describe());12    System.out.println("Created: " + bob.describe());13    14    // No way to create incomplete Person!15    // Person invalid = new Person();  // Won't compile16    17    System.out.println("\n=== Benefits ===");18    System.out.println("✓ Object is fully initialized immediately");19    System.out.println("✓ Can't forget to set required fields");20    System.out.println("✓ Clear what data is needed");21}
    outputCreated: Bob (age 25)
    
    === Benefits ===
    ✓ Object is fully initialized immediately
    ✓ Can't forget to set required fields
    ✓ Clear what data is needed
  1. firstAge ← 30, secondName ← Kai

    1public class ParameterizedConstructor {2    public static void main(String[] args) {3        System.out.println("=== Parameterized Constructor ===\n");4        5        // Create Person with required data6        int firstAge→ 30 = 30;7        String secondName→ Kai = "Kai";8        Person alice = new Person("Alice", firstAge);9        Person bob = new Person(secondName, 25);
    output=== Parameterized Constructor ===
  2. this.name ← Alice, this.age ← 30, alice ← ⟨Person A⟩

    pass 1 of 2
    7        String secondName = "Kai";8        Person alice→ ⟨Person A⟩ = new Person("Alice", firstAge);9        Person bob = new Person(secondName, 25);10        11        System.out.println("Created: " + alice.describe());12        System.out.println("Created: " + bob.describe());13        14        // No way to create incomplete Person!15        // Person invalid = new Person();  // Won't compile16        17        System.out.println("\n=== Benefits ===");18        System.out.println("✓ Object is fully initialized immediately");19        System.out.println("✓ Can't forget to set required fields");20        System.out.println("✓ Clear what data is needed");21    }22}2324class Person {25    String name;26    int age;27    28    // Parameterized constructor29    Person(String nameAlice, int age30) {30        this.name→ Alice = nameAlice;31        this.age→ 30 = age30;32    }
  3. this.name ← Kai, this.age ← 25, bob ← ⟨Person B⟩

    pass 2 of 2
    8        Person alice = new Person("Alice", firstAge);9        Person bob→ ⟨Person B⟩ = new Person(secondName, 25);10        11        System.out.println("Created: " + alice.describe());12        System.out.println("Created: " + bob.describe());13        14        // No way to create incomplete Person!15        // Person invalid = new Person();  // Won't compile16        17        System.out.println("\n=== Benefits ===");18        System.out.println("✓ Object is fully initialized immediately");19        System.out.println("✓ Can't forget to set required fields");20        System.out.println("✓ Clear what data is needed");21    }22}2324class Person {25    String name;26    int age;27    28    // Parameterized constructor29    Person(String nameKai, int age25) {30        this.name→ Kai = nameKai;31        this.age→ 25 = age25;32    }
  4. String describe()

    pass 1 of 2
    34String describe() {35    return nameAlice + " (age " + age30 + ")";36}
  5. System.out.println("Created: " + alice.describe());

    11System.out.println("Created: " + alice.describe());12System.out.println("Created: " + bob.describe());
    outputCreated: Alice (age 30)
  6. String describe()

    pass 2 of 2
    34String describe() {35    return nameKai + " (age " + age25 + ")";36}
  7. System.out.println("Created: " + bob.describe());

    11    System.out.println("Created: " + alice.describe());12    System.out.println("Created: " + bob.describe());13    14    // No way to create incomplete Person!15    // Person invalid = new Person();  // Won't compile16    17    System.out.println("\n=== Benefits ===");18    System.out.println("✓ Object is fully initialized immediately");19    System.out.println("✓ Can't forget to set required fields");20    System.out.println("✓ Clear what data is needed");21}
    outputCreated: Kai (age 25)
    
    === Benefits ===
    ✓ Object is fully initialized immediately
    ✓ Can't forget to set required fields
    ✓ Clear what data is needed
  1. firstAge ← 30, secondName ← Mina

    1public class ParameterizedConstructor {2    public static void main(String[] args) {3        System.out.println("=== Parameterized Constructor ===\n");4        5        // Create Person with required data6        int firstAge→ 30 = 30;7        String secondName→ Mina = "Mina";8        Person alice = new Person("Alice", firstAge);9        Person bob = new Person(secondName, 25);
    output=== Parameterized Constructor ===
  2. this.name ← Alice, this.age ← 30, alice ← ⟨Person A⟩

    pass 1 of 2
    7        String secondName = "Mina";8        Person alice→ ⟨Person A⟩ = new Person("Alice", firstAge);9        Person bob = new Person(secondName, 25);10        11        System.out.println("Created: " + alice.describe());12        System.out.println("Created: " + bob.describe());13        14        // No way to create incomplete Person!15        // Person invalid = new Person();  // Won't compile16        17        System.out.println("\n=== Benefits ===");18        System.out.println("✓ Object is fully initialized immediately");19        System.out.println("✓ Can't forget to set required fields");20        System.out.println("✓ Clear what data is needed");21    }22}2324class Person {25    String name;26    int age;27    28    // Parameterized constructor29    Person(String nameAlice, int age30) {30        this.name→ Alice = nameAlice;31        this.age→ 30 = age30;32    }
  3. this.name ← Mina, this.age ← 25, bob ← ⟨Person B⟩

    pass 2 of 2
    8        Person alice = new Person("Alice", firstAge);9        Person bob→ ⟨Person B⟩ = new Person(secondName, 25);10        11        System.out.println("Created: " + alice.describe());12        System.out.println("Created: " + bob.describe());13        14        // No way to create incomplete Person!15        // Person invalid = new Person();  // Won't compile16        17        System.out.println("\n=== Benefits ===");18        System.out.println("✓ Object is fully initialized immediately");19        System.out.println("✓ Can't forget to set required fields");20        System.out.println("✓ Clear what data is needed");21    }22}2324class Person {25    String name;26    int age;27    28    // Parameterized constructor29    Person(String nameMina, int age25) {30        this.name→ Mina = nameMina;31        this.age→ 25 = age25;32    }
  4. String describe()

    pass 1 of 2
    34String describe() {35    return nameAlice + " (age " + age30 + ")";36}
  5. System.out.println("Created: " + alice.describe());

    11System.out.println("Created: " + alice.describe());12System.out.println("Created: " + bob.describe());
    outputCreated: Alice (age 30)
  6. String describe()

    pass 2 of 2
    34String describe() {35    return nameMina + " (age " + age25 + ")";36}
  7. System.out.println("Created: " + bob.describe());

    11    System.out.println("Created: " + alice.describe());12    System.out.println("Created: " + bob.describe());13    14    // No way to create incomplete Person!15    // Person invalid = new Person();  // Won't compile16    17    System.out.println("\n=== Benefits ===");18    System.out.println("✓ Object is fully initialized immediately");19    System.out.println("✓ Can't forget to set required fields");20    System.out.println("✓ Clear what data is needed");21}
    outputCreated: Mina (age 25)
    
    === Benefits ===
    ✓ Object is fully initialized immediately
    ✓ Can't forget to set required fields
    ✓ Clear what data is needed

Constructor name matches class name. No return type, not even void.

constructor Special method to initialize objects. Called automatically with `new`.

Constructor overloading

Multiple constructors for different creation scenarios.

ConstructorOverloading.java
Replay: real traced execution (multi-file project)
public class ConstructorOverloading {
    public static void main(String[] args) {
        System.out.println("=== Constructor Overloading ===\n");

        // Multiple ways to create a Book
        Book book1 = new Book();
        System.out.println("1. " + book1.describe());

        Book book2 = new Book("1984");
        System.out.println("2. " + book2.describe());

        Book book3 = new Book("1984", "George Orwell");
        System.out.println("3. " + book3.describe());

        Book book4 = new Book("1984", "George Orwell", 328);
        System.out.println("4. " + book4.describe());

        System.out.println("\n=== Flexibility ===");
        System.out.println("Same class, 4 ways to construct!");
        System.out.println("Choose based on what data you have.");
    }
}

class Book {
    String title;
    String author;
    int pages;

    // Constructor 1: No arguments (defaults)
    Book() {
        title = "Untitled";
        author = "Unknown";
        pages = 0;
    }

    // Constructor 2: Title only
    Book(String title) {
        this.title = title;
        author = "Unknown";
        pages = 0;
    }

    // Constructor 3: Title and author
    Book(String title, String author) {
        this.title = title;
        this.author = author;
        pages = 0;
    }

    // Constructor 4: All fields
    Book(String title, String author, int pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }

    String describe() {
        String result = "\"" + title + "\" by " + author;
        if (pages > 0) {
            result += " (" + pages + " pages)";
        }
        return result;
    }
}
  1. public static void main(String[] args)

    1public class ConstructorOverloading {2    public static void main(String[] args) {3        System.out.println("=== Constructor Overloading ===\n");4        5        // Multiple ways to create a Book  //?ways6        Book book1 = new Book();7        System.out.println("1. " + book1.describe());
    output=== Constructor Overloading ===
  2. title ← Untitled, author ← Unknown, pages ← 0, book1 ← ⟨Book A⟩

    5        // Multiple ways to create a Book  //?ways6        Book book1→ ⟨Book A⟩ = new Book();7        System.out.println("1. " + book1.describe());8        9        Book book2 = new Book("1984");10        System.out.println("2. " + book2.describe());11        12        Book book3 = new Book("1984", "George Orwell");13        System.out.println("3. " + book3.describe());14        15        Book book4 = new Book("1984", "George Orwell", 328);16        System.out.println("4. " + book4.describe());17        18        System.out.println("\n=== Flexibility ===");19        System.out.println("Same class, 4 ways to construct!");20        System.out.println("Choose based on what data you have.");21    }22}2324class Book {25    String title;26    String author;27    int pages;28    29    // Constructor 1: No arguments (defaults)  //?ctr130    Book() {31        title→ Untitled = "Untitled";32        author→ Unknown = "Unknown";33        pages→ 0 = 0;34    }
  3. result ← "Untitled" by Unknown

    pass 1 of 4
    57String describe() {58    String result→ "Untitled" by Unknown = "\"" + titleUntitled + "\" by " + authorUnknown;59    if (pages > 0) {60        result += " (" + pages + " pages)";61    }62    return result"Untitled" by Unknown;63}
    All 4 passes — pass 1 is the card above
    passtitleauthorpagesresult
    1UntitledUnknown"Untitled" by Unknown
    21984Unknown"1984" by Unknown
    31984George Orwell"1984" by George Orwell
    41984George Orwell328"1984" by George Orwell
  4. System.out.println("1. " + book1.describe());

    6Book book1 = new Book();7System.out.println("1. " + book1.describe());89Book book2 = new Book("1984");10System.out.println("2. " + book2.describe());
    output1. "Untitled" by Unknown
  5. this.title ← 1984, author ← Unknown, pages ← 0, book2 ← ⟨Book B⟩

    9        Book book2→ ⟨Book B⟩ = new Book("1984");10        System.out.println("2. " + book2.describe());11        12        Book book3 = new Book("1984", "George Orwell");13        System.out.println("3. " + book3.describe());14        15        Book book4 = new Book("1984", "George Orwell", 328);16        System.out.println("4. " + book4.describe());17        18        System.out.println("\n=== Flexibility ===");19        System.out.println("Same class, 4 ways to construct!");20        System.out.println("Choose based on what data you have.");21    }22}2324class Book {25    String title;26    String author;27    int pages;28    29    // Constructor 1: No arguments (defaults)  //?ctr130    Book() {31        title = "Untitled";32        author = "Unknown";33        pages = 0;34    }35    36    // Constructor 2: Title only  //?ctr237    Book(String title1984) {38        this.title→ 1984 = title1984;39        author→ Unknown = "Unknown";40        pages→ 0 = 0;41    }
  6. System.out.println("2. " + book2.describe());

    9Book book2 = new Book("1984");10System.out.println("2. " + book2.describe());1112Book book3 = new Book("1984", "George Orwell");13System.out.println("3. " + book3.describe());
    output2. "1984" by Unknown
  7. this.title ← 1984, this.author ← George Orwell, pages ← 0, book3 ← ⟨Book C⟩

    12        Book book3→ ⟨Book C⟩ = new Book("1984", "George Orwell");13        System.out.println("3. " + book3.describe());14        15        Book book4 = new Book("1984", "George Orwell", 328);16        System.out.println("4. " + book4.describe());17        18        System.out.println("\n=== Flexibility ===");19        System.out.println("Same class, 4 ways to construct!");20        System.out.println("Choose based on what data you have.");21    }22}2324class Book {25    String title;26    String author;27    int pages;28    29    // Constructor 1: No arguments (defaults)  //?ctr130    Book() {31        title = "Untitled";32        author = "Unknown";33        pages = 0;34    }35    36    // Constructor 2: Title only  //?ctr237    Book(String title) {38        this.title = title;39        author = "Unknown";40        pages = 0;41    }42    43    // Constructor 3: Title and author  //?ctr344    Book(String title1984, String authorGeorge Orwell) {45        this.title→ 1984 = title1984;46        this.author→ George Orwell = authorGeorge Orwell;47        pages→ 0 = 0;48    }
  8. System.out.println("3. " + book3.describe());

    12Book book3 = new Book("1984", "George Orwell");13System.out.println("3. " + book3.describe());1415Book book4 = new Book("1984", "George Orwell", 328);16System.out.println("4. " + book4.describe());
    output3. "1984" by George Orwell
  9. this.title ← 1984, this.author ← George Orwell, this.pages ← 328

    15        Book book4→ ⟨Book D⟩ = new Book("1984", "George Orwell", 328);16        System.out.println("4. " + book4.describe());17        18        System.out.println("\n=== Flexibility ===");19        System.out.println("Same class, 4 ways to construct!");20        System.out.println("Choose based on what data you have.");21    }22}2324class Book {25    String title;26    String author;27    int pages;28    29    // Constructor 1: No arguments (defaults)  //?ctr130    Book() {31        title = "Untitled";32        author = "Unknown";33        pages = 0;34    }35    36    // Constructor 2: Title only  //?ctr237    Book(String title) {38        this.title = title;39        author = "Unknown";40        pages = 0;41    }42    43    // Constructor 3: Title and author  //?ctr344    Book(String title, String author) {45        this.title = title;46        this.author = author;47        pages = 0;48    }49    50    // Constructor 4: All fields  //?ctr451    Book(String title1984, String authorGeorge Orwell, int pages328) {52        this.title→ 1984 = title1984;53        this.author→ George Orwell = authorGeorge Orwell;54        this.pages→ 328 = pages328;55    }
  10. result ← "1984" by George Orwell (328 pages)

    58String result = "\"" + title + "\" by " + author;59if (pages328 > 0) {60    result→ "1984" by George Orwell (328 pages) += " (" + pages328 + " pages)";61}
  11. return result;

    61    }62    return result"1984" by George Orwell (328 pages);63}
  12. System.out.println("4. " + book4.describe());

    15    Book book4 = new Book("1984", "George Orwell", 328);16    System.out.println("4. " + book4.describe());17    18    System.out.println("\n=== Flexibility ===");19    System.out.println("Same class, 4 ways to construct!");20    System.out.println("Choose based on what data you have.");21}
    output4. "1984" by George Orwell (328 pages)
    
    === Flexibility ===
    Same class, 4 ways to construct!
    Choose based on what data you have.

Provide several constructors for flexible object creation.

Constructor chaining

Call one constructor from another.

ConstructorChaining.java
Replay: real traced execution (multi-file project)
public class ConstructorChaining {
    public static void main(String[] args) {
        System.out.println("=== Constructor Chaining with this() ===\n");

        // Create products with different constructors
        Product p1 = new Product();
        Product p2 = new Product("Laptop");
        Product p3 = new Product("Phone", 999.99);
        Product p4 = new Product("Tablet", 599.99, 50);

        System.out.println("1. " + p1.describe());
        System.out.println("2. " + p2.describe());
        System.out.println("3. " + p3.describe());
        System.out.println("4. " + p4.describe());

        System.out.println("\n=== Why Chain? ===");
        System.out.println("✓ Avoids code duplication");
        System.out.println("✓ Single place for initialization logic");
        System.out.println("✓ Easy to maintain");
    }
}

class Product {
    String name;
    double price;
    int stock;

    // Primary constructor - all parameters
    Product(String name, double price, int stock) {
        System.out.println("  [Primary constructor called]");
        this.name = name;
        this.price = price;
        this.stock = stock;
    }

    // Chain to primary with default stock
    Product(String name, double price) {
        this(name, price, 0);  // Calls primary constructor
        System.out.println("  [Two-arg constructor finished]");
    }

    // Chain to two-arg with default price
    Product(String name) {
        this(name, 0.0);  // Calls two-arg constructor
        System.out.println("  [One-arg constructor finished]");
    }

    // Chain to one-arg with default name
    Product() {
        this("Unknown");  // Calls one-arg constructor
        System.out.println("  [No-arg constructor finished]");
    }

    String describe() {
        return name + " ($" + price + ", " + stock + " in stock)";
    }
}
  1. public static void main(String[] args)

    1public class ConstructorChaining {2    public static void main(String[] args) {3        System.out.println("=== Constructor Chaining with this() ===\n");4        5        // Create products with different constructors  //?create6        Product p1 = new Product();7        Product p2 = new Product("Laptop");
    output=== Constructor Chaining with this() ===
  2. this.name ← Unknown, this.price ← 0.0, this.stock ← 0

    pass 1 of 4
    28// Primary constructor - all parameters  //?primary29Product(String nameUnknown, double price0.0, int stock0) {30    System.out.println("  [Primary constructor called]");31    this.name→ Unknown = nameUnknown;32    this.price→ 0.0 = price0.0;33    this.stock→ 0 = stock0;34}
    output  [Primary constructor called]
    All 4 passes — pass 1 is the card above
    passnamepricestockthis.namethis.pricethis.stockp1p2p4
    1Unknown0.00Unknown0.00⟨Product A⟩
    2Laptop0.00Laptop0.00⟨Product B⟩
    3Phone999.990Phone999.990
    4Tablet599.9950Tablet599.9950⟨Product C⟩
  3. Product(String name, double price)

    pass 1 of 3
    36// Chain to primary with default stock  //?chain137Product(String nameUnknown, double price0.0) {38    this(name, price, 0);  // Calls primary constructor39    System.out.println("  [Two-arg constructor finished]");40}
    output  [Two-arg constructor finished]
    All 3 passes — pass 1 is the card above
    passnamepricep1p2p3
    1Unknown0.0⟨Product A⟩
    2Laptop0.0⟨Product B⟩
    3Phone999.99⟨Product D⟩
  4. Product(String name)

    pass 1 of 2
    42// Chain to two-arg with default price43Product(String nameUnknown) {44    this(name, 0.0);  // Calls two-arg constructor45    System.out.println("  [One-arg constructor finished]");46}
    output  [One-arg constructor finished]
  5. p1 ← ⟨Product A⟩

    5        // Create products with different constructors  //?create6        Product p1→ ⟨Product A⟩ = new Product();7        Product p2 = new Product("Laptop");8        Product p3 = new Product("Phone", 999.99);9        Product p4 = new Product("Tablet", 599.99, 50);10        11        System.out.println("1. " + p1.describe());12        System.out.println("2. " + p2.describe());13        System.out.println("3. " + p3.describe());14        System.out.println("4. " + p4.describe());15        16        System.out.println("\n=== Why Chain? ===");17        System.out.println("✓ Avoids code duplication");18        System.out.println("✓ Single place for initialization logic");19        System.out.println("✓ Easy to maintain");20    }21}2223class Product {24    String name;25    double price;26    int stock;27    28    // Primary constructor - all parameters  //?primary29    Product(String name, double price, int stock) {30        System.out.println("  [Primary constructor called]");31        this.name = name;32        this.price = price;33        this.stock = stock;34    }35    36    // Chain to primary with default stock  //?chain137    Product(String name, double price) {38        this(name, price, 0);  // Calls primary constructor39        System.out.println("  [Two-arg constructor finished]");40    }41    42    // Chain to two-arg with default price43    Product(String name) {44        this(name, 0.0);  // Calls two-arg constructor45        System.out.println("  [One-arg constructor finished]");46    }47    48    // Chain to one-arg with default name  //?chain049    Product() {50        this("Unknown");  // Calls one-arg constructor51        System.out.println("  [No-arg constructor finished]");52    }
    output  [No-arg constructor finished]
  6. p2 ← ⟨Product B⟩

    pass 2 of 2
    6        Product p1 = new Product();7        Product p2→ ⟨Product B⟩ = new Product("Laptop");8        Product p3 = new Product("Phone", 999.99);9        Product p4 = new Product("Tablet", 599.99, 50);10        11        System.out.println("1. " + p1.describe());12        System.out.println("2. " + p2.describe());13        System.out.println("3. " + p3.describe());14        System.out.println("4. " + p4.describe());15        16        System.out.println("\n=== Why Chain? ===");17        System.out.println("✓ Avoids code duplication");18        System.out.println("✓ Single place for initialization logic");19        System.out.println("✓ Easy to maintain");20    }21}2223class Product {24    String name;25    double price;26    int stock;27    28    // Primary constructor - all parameters  //?primary29    Product(String name, double price, int stock) {30        System.out.println("  [Primary constructor called]");31        this.name = name;32        this.price = price;33        this.stock = stock;34    }35    36    // Chain to primary with default stock  //?chain137    Product(String name, double price) {38        this(name, price, 0);  // Calls primary constructor39        System.out.println("  [Two-arg constructor finished]");40    }41    42    // Chain to two-arg with default price43    Product(String nameLaptop) {44        this(name, 0.0);  // Calls two-arg constructor45        System.out.println("  [One-arg constructor finished]");46    }
    output  [One-arg constructor finished]
  7. String describe()

    pass 1 of 4
    54String describe() {55    return nameUnknown + " ($" + price0.0 + ", " + stock0 + " in stock)";56}
    All 4 passes — pass 1 is the card above
    passnamepricestock
    1Unknown0.00
    2Laptop0.00
    3Phone999.990
    4Tablet599.9950
  8. System.out.println("1. " + p1.describe());

    11System.out.println("1. " + p1.describe());12System.out.println("2. " + p2.describe());13System.out.println("3. " + p3.describe());
    output1. Unknown ($0.0, 0 in stock)
  9. System.out.println("2. " + p2.describe());

    11System.out.println("1. " + p1.describe());12System.out.println("2. " + p2.describe());13System.out.println("3. " + p3.describe());14System.out.println("4. " + p4.describe());
    output2. Laptop ($0.0, 0 in stock)
  10. System.out.println("3. " + p3.describe());

    12System.out.println("2. " + p2.describe());13System.out.println("3. " + p3.describe());14System.out.println("4. " + p4.describe());
    output3. Phone ($999.99, 0 in stock)
  11. System.out.println("4. " + p4.describe());

    13    System.out.println("3. " + p3.describe());14    System.out.println("4. " + p4.describe());15    16    System.out.println("\n=== Why Chain? ===");17    System.out.println("✓ Avoids code duplication");18    System.out.println("✓ Single place for initialization logic");19    System.out.println("✓ Easy to maintain");20}
    output4. Tablet ($599.99, 50 in stock)
    
    === Why Chain? ===
    ✓ Avoids code duplication
    ✓ Single place for initialization logic
    ✓ Easy to maintain

this(args) calls another constructor. Must be first statement.

this() Call another constructor: `this(args)`. Avoids duplicating initialization code.

Validate in constructor

Reject invalid data at creation time.

Validation.java
Replay: real traced execution (multi-file project)
public class Validation {
    public static void main(String[] args) {
        System.out.println("=== Validation in Constructors ===\n");

        // Valid accounts
        Account acc1 = new Account("ACC001", 100.0);
        System.out.println("Created: " + acc1.describe());

        Account acc2 = new Account("ACC002", 0.0);
        System.out.println("Created: " + acc2.describe());

        System.out.println("\n=== Invalid Attempts ===");

        // Invalid: null ID
        try {
            new Account(null, 100.0);
        } catch (IllegalArgumentException e) {
            System.out.println("Rejected null ID: " + e.getMessage());
        }

        // Invalid: empty ID
        try {
            new Account("", 100.0);
        } catch (IllegalArgumentException e) {
            System.out.println("Rejected empty ID: " + e.getMessage());
        }

        // Invalid: negative balance
        try {
            new Account("ACC003", -50.0);
        } catch (IllegalArgumentException e) {
            System.out.println("Rejected negative: " + e.getMessage());
        }

        System.out.println("\n=== Benefit ===");
        System.out.println("Invalid objects can NEVER be created!");
    }
}

class Account {
    final String id;
    double balance;

    Account(String id, double balance) {
        // Validate ID
        if (id == null || id.isEmpty()) {
            throw new IllegalArgumentException("ID cannot be null or empty");
        }

        // Validate balance
        if (balance < 0) {
            throw new IllegalArgumentException("Balance cannot be negative");
        }

        // All validations passed - initialize
        this.id = id;
        this.balance = balance;
    }

    String describe() {
        return "Account " + id + ": $" + balance;
    }
}
  1. public static void main(String[] args)

    1public class Validation {2    public static void main(String[] args) {3        System.out.println("=== Validation in Constructors ===\n");4        5        // Valid accounts  //?valid6        Account acc1 = new Account("ACC001", 100.0);7        System.out.println("Created: " + acc1.describe());
    output=== Validation in Constructors ===
  2. this.id ← ACC001, this.balance ← 100.0, acc1 ← ⟨Account A⟩

    pass 1 of 5
    5        // Valid accounts  //?valid6        Account acc1→ ⟨Account A⟩ = new Account("ACC001", 100.0);7        System.out.println("Created: " + acc1.describe());8        9        Account acc2 = new Account("ACC002", 0.0);10        System.out.println("Created: " + acc2.describe());11        12        System.out.println("\n=== Invalid Attempts ===");13        14        // Invalid: null ID  //?invalid15        try {16            new Account(null, 100.0);17        } catch (IllegalArgumentException e) {18            System.out.println("Rejected null ID: " + e.getMessage());19        }20        21        // Invalid: empty ID22        try {23            new Account("", 100.0);24        } catch (IllegalArgumentException e) {25            System.out.println("Rejected empty ID: " + e.getMessage());26        }27        28        // Invalid: negative balance29        try {30            new Account("ACC003", -50.0);31        } catch (IllegalArgumentException e) {32            System.out.println("Rejected negative: " + e.getMessage());33        }34        35        System.out.println("\n=== Benefit ===");36        System.out.println("Invalid objects can NEVER be created!");37    }38}3940class Account {41    final String id;  //?final42    double balance;43    44    Account(String idACC001, double balance100.0) {  //?validate45        // Validate ID46        if (id == null || id.isEmpty()) {  //?checkid47            throw new IllegalArgumentException("ID cannot be null or empty");48        }49        50        // Validate balance51        if (balance < 0) {  //?checkbalance52            throw new IllegalArgumentException("Balance cannot be negative");53        }54        55        // All validations passed - initialize56        this.id→ ACC001 = idACC001;57        this.balance→ 100.0 = balance100.0;58    }
    All 5 passes — pass 1 is the card above
    passidbalanceethis.idthis.balanceacc1acc2
    1ACC001100.0ACC001100.0⟨Account A⟩
    2ACC0020.0ACC0020.0⟨Account B⟩
    3null100.0java.lang.IllegalArgumentException: ID cannot be null or empty
    4(empty)100.0java.lang.IllegalArgumentException: ID cannot be null or empty
    5ACC003-50.0java.lang.IllegalArgumentException: Balance cannot be negative
  3. String describe()

    pass 1 of 2
    60String describe() {61    return "Account " + idACC001 + ": $" + balance100.0;62}
  4. System.out.println("Created: " + acc1.describe());

    6Account acc1 = new Account("ACC001", 100.0);7System.out.println("Created: " + acc1.describe());89Account acc2 = new Account("ACC002", 0.0);10System.out.println("Created: " + acc2.describe());
    outputCreated: Account ACC001: $100.0
  5. String describe()

    pass 2 of 2
    60String describe() {61    return "Account " + idACC002 + ": $" + balance0.0;62}
  6. System.out.println("Created: " + acc2.describe());

    9Account acc2 = new Account("ACC002", 0.0);10System.out.println("Created: " + acc2.describe());1112System.out.println("\n=== Invalid Attempts ===");
    outputCreated: Account ACC002: $0.0
    
    === Invalid Attempts ===
  7. if (id == null || id.isEmpty())

    pass 1 of 2
    45// Validate ID46if (idnull == null || id.isEmpty()) {  //?checkid47    throw new IllegalArgumentException("ID cannot be null or empty");48}
  8. catch (IllegalArgumentException e)

    16    new Account(null, 100.0);17} catch (IllegalArgumentException ejava.lang.IllegalArgumentException: ID cannot be null or empty) {18    System.out.println("Rejected null ID: " + e.getMessage());19}
    outputRejected null ID: ID cannot be null or empty
  9. if (id == null || id.isEmpty())

    pass 2 of 2
    45// Validate ID46if (id(empty) == null || id.isEmpty()) {  //?checkid47    throw new IllegalArgumentException("ID cannot be null or empty");48}
  10. catch (IllegalArgumentException e)

    23    new Account("", 100.0);24} catch (IllegalArgumentException ejava.lang.IllegalArgumentException: ID cannot be null or empty) {25    System.out.println("Rejected empty ID: " + e.getMessage());26}
    outputRejected empty ID: ID cannot be null or empty
  11. if (balance < 0)

    50// Validate balance51if (balance-50.0 < 0) {  //?checkbalance52    throw new IllegalArgumentException("Balance cannot be negative");53}
  12. catch (IllegalArgumentException e)

    30    new Account("ACC003", -50.0);31} catch (IllegalArgumentException ejava.lang.IllegalArgumentException: Balance cannot be negative) {32    System.out.println("Rejected negative: " + e.getMessage());33}
    outputRejected negative: Balance cannot be negative
  13. System.out.println(" === Benefit ===");

    35    System.out.println("\n=== Benefit ===");36    System.out.println("Invalid objects can NEVER be created!");37}
    output
    === Benefit ===
    Invalid objects can NEVER be created!

Throw exceptions for invalid arguments. Prevent invalid objects from existing.

Exercise: CompleteExample.java

Create a complete class with multiple constructors and validation