Understanding Java Constructors: Types, Examples, and Best Practices

In this article, we will explore Java constructors, their types, and provide examples to illustrate each type.

What is a Constructor?

A constructor is a special type of method in Java that has the same name as the class. Its primary purpose is to initialize objects when they are created.

Example of a Java Constructor

class DemoExample {
    DemoExample() {
        // constructor body
    }
}

In this example, DemoExample() is a constructor. It shares the same name as the class and does not have a return type, not even void.

Key Features of Constructors

  • Constructors do not have a return type.
  • They are called automatically when an object is created.

Types of Constructors

There are three main types of constructors in Java:

  • No-Arguments Constructor
  • Parameterized Constructor
  • Default Constructor

1. No-Arguments Constructor

A no-arguments constructor is a constructor that does not take any parameters.

Example of a No-Arguments Constructor

class Rectangle {
    double length, width;

    // No-argument constructor
    Rectangle() {
        setDetails(52, 47);
    }

    void setDetails(double l, double w) {
        length = l;
        width = w;
    }

    void display() {
        System.out.println("-----------------------");
        System.out.println("Length: " + length);
        System.out.println("Width: " + width);
        System.out.println("Area: " + calcArea());
    }

    double calcArea() {
        return length * width;
    }
}

class ConstructorDemo1 {
    public static void main(String[] args) {
        Rectangle r1 = new Rectangle();
        r1.display();
    }
}

Output of Example 2

-----------------------
Length: 52.0
Width: 47.0
Area: 2444.0

2. Parameterized Constructor

A parameterized constructor is one that accepts one or more parameters. This allows you to initialize an object with specific values at the time of creation.

Example of a Parameterized Constructor

class Rectangle {
    double length, width;

    // Parameterized constructor
    Rectangle(double l, double w) {
        setDetails(l, w);
    }

    void setDetails(double l, double w) {
        length = l;
        width = w;
    }

    void display() {
        System.out.println("-----------------------");
        System.out.println("Length: " + length);
        System.out.println("Width: " + width);
        System.out.println("Area: " + calcArea());
    }

    double calcArea() {
        return length * width;
    }
}

class ConstructorDemo2 {
    public static void main(String[] args) {
        Rectangle r1 = new Rectangle(101, 70);
        r1.display();
    }
}

Output of Example 3

-----------------------
Length: 101.0
Width: 70.0
Area: 7070.0

3. Default Constructor

A default constructor is automatically created by the Java compiler if no constructors are explicitly defined in the class. This constructor does not take any parameters and initializes instance variables with default values.

Example of a Default Constructor

class Rectangle {
    double length, width;

    void display() {
        System.out.println("-----------------------");
        System.out.println("Length: " + length);
        System.out.println("Width: " + width);
    }
}

class ConstructorDemo3 {
    public static void main(String[] args) {
        Rectangle r1 = new Rectangle();
        r1.display();
    }
}

Output of Example 4

-----------------------
Length: 0.0
Width: 0.0

The default constructor initializes uninitialized instance variables with default values:

TypeDefault Value
booleanfalse
byte0
short0
int0
long0L
char\u0000
float0.0f
double0.0d
objectnull

Summary

  • Constructors are called automatically when an object is created.

  • The name of the constructor must match the class name, and it cannot have a return type.

  • If a class does not define any constructors, the Java compiler automatically provides a default constructor.

  • Types of Constructors: Certainly! Here’s the continuation of the summary and the conclusion of your article:

    • No-Argument Constructor: Does not accept any parameters and initializes instance variables with default values or predefined values.
    • Parameterized Constructor: Accepts one or more parameters, allowing for the initialization of an object with specific values at the time of creation.
    • Default Constructor: Automatically created by the Java compiler if no constructors are explicitly defined. It initializes instance variables with default values.
  • A constructor cannot be declared as static, abstract, or final.

Additional Notes

  • Constructor Overloading: You can have multiple constructors in a class with different parameter lists. This is known as constructor overloading, which allows you to create objects in different ways.

    class Rectangle {
        double length, width;
    
        // No-argument constructor
        Rectangle() {
            length = 0;
            width = 0;
        }
    
        // Parameterized constructor
        Rectangle(double l, double w) {
            length = l;
            width = w;
        }
    }
    
  • Chaining Constructors: You can call one constructor from another within the same class using the this() keyword. This is useful for reusing constructor code.

    class Rectangle {
        double length, width;
    
        // No-argument constructor
        Rectangle() {
            this(0, 0); // Calls the parameterized constructor
        }
    
        // Parameterized constructor
        Rectangle(double l, double w) {
            length = l;
            width = w;
        }
    }
    

Conclusion

Understanding constructors is fundamental to working with objects in Java. They play a crucial role in initializing objects and ensuring that they are in a valid state when created. By mastering the different types of constructors and their features, you can write more efficient and organized Java code.

We hope you found this article helpful! If you have any questions or would like to learn more about Java, feel free to reach out.

Happy coding! 😄

Vishnu Damwala
Vishnu Damwala

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳