You are currently viewing Java Constructors
java_logo

Java Constructors

1. Creating Constructors

Constructors are special methods used to initialize objects. They have the same name as the class and do not have a return type, not even void.

public class MyClass {
    // Constructor declaration
    public MyClass() {
        // Constructor body
    }
}

In the example above, we declare a constructor for the MyClass class. It has the same name as the class and is denoted by the absence of a return type. The constructor body will contain the initialization logic, as we will see in the next chapter.

2. Instantiating Objects using Constructors

The primary purpose of a constructor is to initialize the object’s state, set up resources, and perform any necessary setup tasks.

2.1. Types of Constructors

Default Constructor:

If a class doesn’t explicitly define any constructors, Java provides a default constructor.
It initializes instance variables to their default values (e.g., numerical types to 0, references to null).

MyClass obj = new MyClass(); // calls the default constructor

Parameterized Constructor:

A constructor with parameters allows you to initialize an object with specific values during creation.
It enables you to customize the initialization process based on the arguments provided.

MyClass obj = new MyClass(arg1, arg2); // calls the parameterized constructor

example:

public class Person {
    private String name;

    // Default Constructor
    public Person() {
        this.name = "John Doe";
        System.out.println("Default Constructor: A new person is created with the default name.");
    }

    // Parameterized Constructor
    public Person(String name) {
        this.name = name;
        System.out.println("Parameterized Constructor: A new person is created with the custom name.");
    }

    // Getter method (for illustration purposes)
    public String getName() {
        return name;
    }

    public static void main(String[] args) {
        // Using the Default Constructor
        Person defaultPerson = new Person();
        System.out.println("Name: " + defaultPerson.getName());
        System.out.println();

        // Using the Parameterized Constructor
        Person customPerson = new Person("Alice");
        System.out.println("Name: " + customPerson.getName());
    }
}

In this example, we have a Person class with a single variable name and two constructors:

Default Constructor:
Initializes name to “John Doe” by default.
Outputs a message indicating that a new person is created with the default name.

Parameterized Constructor:
Takes name as a parameter and sets the corresponding field.
Outputs a message indicating that a new person is created with a custom name.

Output of the program:

Default Constructor: A new person is created with the default name.
Name: John Doe

Parameterized Constructor: A new person is created with the custom name.
Name: Alice