Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 2 of 10
Constructors - Controlled Initialisation
A constructor is a special method with the same name as the class and no return type. It runs automatically when you use new. Constructors ensure objects are always created in a valid, complete state - preventing partially-initialised objects that cause bugs.
Constructor Types
- Default constructor - no-arg, provided by Java only if you define NO constructors. Sets fields to defaults (0, false, null).
- No-arg constructor - explicitly defined, allows custom default initialisation.
- Parameterised constructor - accepts arguments to set fields on creation. Most common in practice.
- Constructor overloading - multiple constructors with different parameter lists.
- Constructor chaining - one constructor calls another with this(...)
Constructors in the Book Class
public class Book {
private final String isbn; // final: must be set in constructor, never changes
private String title;
private String author;
private double price;
private boolean available;
// Parameterised constructor - preferred pattern
public Book(String isbn, String title, String author, double price) {
// Defensive validation - guard clause
if (isbn == null || isbn.isBlank()) throw new IllegalArgumentException("ISBN required");
if (price < 0) throw new IllegalArgumentException("Price cannot be negative");
this.isbn = isbn; // 'this.field' disambiguates field from parameter
this.title = title;
this.author = author;
this.price = price;
this.available = true; // sensible default: new book is available
}
// Overloaded: convenience constructor for books without a known price
public Book(String isbn, String title, String author) {
this(isbn, title, author, 0.0); // delegates to main constructor
}
// toString - human-readable representation (good practice to always override)
@Override
public String toString() {
return String.format("Book{isbn='%s', title='%s', author='%s', price=%.2f, available=%s}",
isbn, title, author, price, available);
}
// Getters (no setters for isbn - it's immutable)
public String getIsbn() { return isbn; }
public String getTitle() { return title; }
public String getAuthor() { return author; }
public double getPrice() { return price; }
public boolean isAvailable() { return available; }
public void setAvailable(boolean available) { this.available = available; }
public void setPrice(double price) {
if (price < 0) throw new IllegalArgumentException("Price cannot be negative");
this.price = price;
}
}
// Usage:
// Book book = new Book("978-0132350884", "Clean Code", "Robert Martin", 39.99);
// Book free = new Book("000-0000000000", "Free Guide", "Team"); // price defaults to 0Quick Quiz
Tip
Tip
Practice Constructors Controlled Initialisation in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Constructors - Controlled Initialisation
Practice Task
Note
Practice Task - (1) Write a working example of Constructors Controlled Initialisation from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Constructors Controlled Initialisation is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Key Takeaways
- A constructor is a special method with the same name as the class and no return type.
- Default constructor - no-arg, provided by Java only if you define NO constructors. Sets fields to defaults (0, false, null).
- No-arg constructor - explicitly defined, allows custom default initialisation.
- Parameterised constructor - accepts arguments to set fields on creation. Most common in practice.
Finished this lesson?