Skip to content
QuizMaker logoQuizMaker
Activity
Java Programming: From Zero to Enterprise
2. Object-Oriented Programming
1. Getting Started with Java & the JVM
2. Data Types & Variables
3. Control Flow: Ifs & Loops
4. String Manipulation in Depth
5. Methods (Functions) Architecture
6. Arrays & The Enhanced For Loop
7. User Input via Scanner
8. Mathematical Operations & The Math Class
9. Operators in Depth
10. Block Scope & Variable Lifecycles
11. Introduction to Object-Oriented Programming
12. Classes & Instances Deep Dive
13. Constructors
14. Encapsulation & The 'this' Keyword
15. Inheritance: Extending Functionality
16. Polymorphism & Method Overriding
17. Abstraction & Abstract Classes
18. Interfaces: The Ultimate Contract
19. Packages & Access Modifiers
20. Enums (Enumerations)
21. Exceptions: Handling Runtime Errors
22. The 'throw' and 'throws' keywords
23. Dates, Times, and Formatting
24. Enumerable Data Structures
25. LinkedLists: The Alternative
26. HashMaps: Key-Value Architecture
27. HashSets: The Art of Uniqueness
28. Iterator: Safe Collection Traversal
29. Wrapper Classes & Autoboxing
30. Basic File I/O
31. Generics: Type-Safe Templates
32. Lambda Expressions & Functional Interfaces
33. The Stream API: Functional Data Pipelines
34. Optional: Beating the NullPointerException
35. Multithreading & Concurrency Basics
36. JDBC: Connecting to SQL Databases
37. Annotations & Reflection
38. The JVM Garbage Collector
39. Introduction to Spring Boot
40. Unit Testing with JUnit
41. Java Collections for DSA
CONTENTS

13. Constructors

Initializing objects properly the moment they are born.

Java Programming: From Zero to Enterprise
2. Object-Oriented Programming
February 22, 2026
64
A

[!NOTE] When you use the new keyword, Java executes a special method called a Constructor right as the object is being built. This is your opportunity to force required parameters upon creation.

The Constructor Method

A constructor is a highly specialized method that serves exactly one purpose: initializing the state of a new object.

Rules of a Constructor:

  1. Its name must exactly match the Class name.
  2. It cannot have a return type (not even void).
  3. It is called automatically the moment new is executed.
public class Car {
    String modelName;
    int manufacturingYear;

    // This is the Constructor!
    public Car(String name, int year) {
        modelName = name;
        manufacturingYear = year;
        System.out.println("A new " + name + " has rolled off the assembly line.");
    }

    public static void main(String[] args) {
        // You MUST provide the parameters when calling 'new'!
        Car myCar = new Car("Mustang", 1969); 
    }
}

Constructor Overloading

What if you want to give developers multiple ways to build an object? Maybe occasionally they know the manufacturing year, but sometimes they just want a default "Blank" car?

You can overload constructors by writing multiple constructors with different parameter signatures. The JVM will automatically figure out which one you are trying to use based on the arguments you pass.

public class User {
    String email;
    String role;

    // Constructor 1: Fully custom
    public User(String emailArg, String roleArg) {
        email = emailArg;
        role = roleArg;
    }

    // Constructor 2: Assumes a default 'guest' role!
    public User(String emailArg) {
        email = emailArg;
        role = "guest"; 
    }

    public static void main(String[] args) {
        User admin = new User("admin@site.com", "admin_role"); // Calls Constructor 1
        User random = new User("rando@site.com");              // Calls Constructor 2
    }
}

[!CAUTION] If you do not write a single constructor in your class, Java secretly compiles an invisible, empty "Default Constructor" for you so new Car() works. However, the moment you explicitly write any parameterized constructor, the invisible default one is destroyed! You must manually re-add an empty public Car() {} if you want it back.

Constructors Protect Object Validity

A constructor should leave an object ready to use. If a User must always have an email, the constructor is a good place to require it. This prevents half-created objects from spreading through your program.

Validate During Construction

class User {
    private String email;

    User(String email) {
        if (email == null || email.isBlank()) {
            throw new IllegalArgumentException("Email is required");
        }
        this.email = email;
    }
}

Throwing an exception here is better than allowing a broken User object and discovering the problem much later.

Constructor Chaining

class Product {
    String name;
    double price;

    Product(String name) {
        this(name, 0.0);
    }

    Product(String name, double price) {
        this.name = name;
        this.price = price;
    }
}

this(...) calls another constructor in the same class. It helps keep default setup logic in one place.

Common Mistakes

  • Adding a return type to a constructor, which turns it into a normal method.
  • Writing validation in many methods instead of creating valid objects from the start.
  • Forgetting that adding one constructor removes Java's implicit no-argument constructor.
  • Duplicating initialization logic across overloaded constructors.

Mini Practice

Create a Course class whose constructor requires a non-empty title and a positive duration. Add an overloaded constructor that uses a default duration.

Practice Lab: Valid Objects From Birth

Use constructors to prevent incomplete objects.

  1. Create a Course class with title, duration hours, and difficulty.
  2. Write a constructor requiring all three values.
  3. Reject empty title and non-positive duration with IllegalArgumentException.
  4. Add an overloaded constructor that sets difficulty to beginner.

Goal: Practice required initialization, validation, and constructor overloading.

Revision Checkpoint

  • Constructor name: Must match the class name.
  • No return type: Constructors do not declare void.
  • Purpose: Initialize a new object into a valid state.
  • Overloading: Multiple constructors can provide different creation paths.
  • this(...): Calls another constructor in the same class.

Before the quiz: Identify whether a code block is a constructor or a normal method.

Share this article

Share on TwitterShare on LinkedInShare on FacebookShare on WhatsAppShare on Email

Test your knowledge

Take a quick quiz based on this chapter.

mediumJava
Quiz: Constructors
10 questions5 min
Lesson 3 of 10 in 2. Object-Oriented Programming
Previous in 2. Object-Oriented Programming
12. Classes & Instances Deep Dive
Next in 2. Object-Oriented Programming
14. Encapsulation & The 'this' Keyword
Back to Java Programming: From Zero to Enterprise
Back to moduleCategories