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.

Feb 22, 20263 views0 likes0 fires
18px

[!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.

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
2 questions5 min

Continue Learning

14. Encapsulation & The 'this' Keyword

Intermediate
12 min

15. Inheritance: Extending Functionality

Intermediate
14 min

16. Polymorphism & Method Overriding

Intermediate
12 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 Java Programming: From Zero to EnterpriseAll Categories