Lesson 12 of 25

Constructors

Creating Constructors

A constructor initializes an object when it's created. It has the same name as the class and no return type.

Example
public class User {
    private String name;
    private String email;
    private int age;

    // Default constructor
    public User() {
        this.name = "Unknown";
        this.email = "";
        this.age = 0;
    }

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

    // Constructor chaining with this()
    public User(String name, String email) {
        this(name, email, 0); // calls the 3-parameter constructor
    }
}

// Usage
User u1 = new User();                          // default
User u2 = new User("Alice", "a@b.com", 25);   // parameterized
User u3 = new User("Bob", "b@b.com");          // chained