Skip to content

Constructors – Special Methods for Creating Objects

Seanti edited this page Mar 24, 2025 · 1 revision

Now that we understand classes and objects, let’s explore constructors—special methods that help create objects! 🚀


1. What is a Constructor?

A constructor is a special method inside a class that runs automatically when an object is created.

Think of it like building a new house:

  • 🏗️ The constructor = the blueprint’s setup instructions.
  • 🏡 The object = the house built using those instructions.

2. Basic Constructor Example

Let’s create a class called Car with a constructor:

class Car {
    String brand;  // Car brand
    int year;  // Car year

    // Constructor (same name as the class)
    Car(String carBrand, int carYear) {
        brand = carBrand;
        year = carYear;
    }

    void displayInfo() {
        System.out.println("Car: " + brand + ", Year: " + year);
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car("Toyota", 2023); // Constructor runs automatically!
        myCar.displayInfo();
    }
}

Output:

Car: Toyota, Year: 2023

3. How Does This Work?

Constructor Rules:

Same name as the class (Car).
No return type (not even void).
Runs automatically when you create an object.

new Car("Toyota", 2023); → The constructor assigns values to brand and year!


4. Default vs. Parameterized Constructors

A. Default Constructor (No Parameters)

If we don’t create a constructor, Java automatically gives us a default constructor (empty).

class Dog {
    Dog() { // Default constructor
        System.out.println("A new dog is created!");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog(); // Calls the default constructor
    }
}

Output:

A new dog is created!

B. Parameterized Constructor (With Parameters)

We can pass values to the constructor to customize the object.

class Dog {
    String name;

    Dog(String dogName) {  // Parameterized constructor
        name = dogName;
    }

    void bark() {
        System.out.println(name + " says: Woof! 🐶");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog("Buddy"); // Pass "Buddy" to constructor
        myDog.bark();
    }
}

Output:

Buddy says: Woof! 🐶

5. Multiple Constructors – Constructor Overloading

Just like methods, constructors can be overloaded (multiple constructors with different parameters).

class Student {
    String name;
    int age;

    // Constructor 1: No parameters
    Student() {
        name = "Unknown";
        age = 0;
    }

    // Constructor 2: With parameters
    Student(String studentName, int studentAge) {
        name = studentName;
        age = studentAge;
    }

    void display() {
        System.out.println("Student: " + name + ", Age: " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student(); // Calls constructor 1
        Student s2 = new Student("Alice", 20); // Calls constructor 2

        s1.display();
        s2.display();
    }
}

Output:

Student: Unknown, Age: 0
Student: Alice, Age: 20

🔹 If no values are provided → Uses the default values from constructor 1.
🔹 If values are provided → Uses constructor 2.


6. this Keyword – Referring to the Current Object

When parameter names are the same as instance variables, we use this to avoid confusion.

class Person {
    String name;

    // Using "this" to refer to instance variable
    Person(String name) {
        this.name = name;
    }

    void introduce() {
        System.out.println("Hi, my name is " + name);
    }
}

public class Main {
    public static void main(String[] args) {
        Person p1 = new Person("Emma");
        p1.introduce();
    }
}

Output:

Hi, my name is Emma

this.name = name; → Assigns parameter value to the instance variable.


7. Why Use Constructors?

Without Constructor With Constructor
Must set values manually after object creation. Values are set automatically when the object is created.
More code, harder to manage. Less code, cleaner and easier.

Example without constructor (longer and repetitive):

class Car {
    String brand;
    int year;
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.brand = "Toyota"; // Manual assignment
        myCar.year = 2023;
        System.out.println(myCar.brand + " - " + myCar.year);
    }
}

With Constructor: Faster, cleaner, and automatic!

class Car {
    String brand;
    int year;

    Car(String carBrand, int carYear) {
        brand = carBrand;
        year = carYear;
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car("Toyota", 2023); // Values set automatically!
        System.out.println(myCar.brand + " - " + myCar.year);
    }
}

8. Quick Recap – Constructor Cheat Sheet

Concept Description
Constructor A special method that runs when an object is created.
Default Constructor Has no parameters, assigns default values.
Parameterized Constructor Takes arguments to set initial values.
Constructor Overloading Multiple constructors with different parameters.
this Keyword Refers to current object to avoid confusion.

9. What’s Next?

Now that we understand constructors, we’ll explore method overloading—how to create multiple methods with the same name but different parameters! 🚀

Clone this wiki locally