Back to course

Creating Objects with Constructors (Default and Parameterized)

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 16: Creating Objects with Constructors

A constructor is a special type of method used for initializing an object immediately after memory is allocated for it. It runs only once when the object is created.

Key Characteristics of Constructors

  1. A constructor's name must be exactly the same as the class name.
  2. It has no return type (not even void).
  3. It is called using the new keyword.

1. The Default Constructor

If you do not define any constructor explicitly, Java provides a public, no-argument (default) constructor automatically.

java public class Book { String title;

// Java provides this automatically if we don't write it:
// public Book() { }

}

Book b = new Book(); // Calls the default constructor

2. Parameterized Constructors

Used to force the caller to provide initial values for the object's state.

java public class Book { String title; int pages;

// Parameterized Constructor
public Book(String initialTitle, int numPages) {
    title = initialTitle;
    pages = numPages;
    System.out.println("New book initialized: " + title);
}

}

// Must pass arguments when creating the object Book harryPotter = new Book("Harry Potter", 300); // Book emptyBook = new Book(); // ERROR! Default constructor is gone.

3. Constructor Overloading

A class can have multiple constructors, as long as each one has a unique parameter list (different number or types of parameters). This is useful for providing flexibility in object creation.

java public class Book { // 1. Constructor with title and pages public Book(String title, int pages) { ... }

// 2. Constructor with title only
public Book(String title) { 
    this(title, 0); // Calls the first constructor (Constructor chaining)
}

}