DEV Community

Cover image for Understanding Constructors in Java: A Beginner's Guide
arun Kumar
arun Kumar

Posted on

Understanding Constructors in Java: A Beginner's Guide

Java is one of the most widely used object-oriented programming languages, and constructors play an important role in creating and initializing objects. If you're new to Java, understanding constructors is essential because they help set up an object's initial state when it is created.

What is a Constructor?

A constructor is a special method in Java that is automatically called when an object of a class is created. Its main purpose is to initialize the object's data members.

Unlike regular methods, constructors have the same name as the class and do not have a return type.

Why Do We Need Constructors?

Constructors help initialize objects with default or user-defined values. Without constructors, you would need to assign values manually after creating every object.

Benefits of Constructors

  • Automatically initializes object data.
  • Reduces repetitive code.
  • Improves code readability.
  • Makes object creation easier.
  • Supports object-oriented programming principles.

Example of a Constructor
class Student {

String name;

Student() {
    name = "Arun";
}

void display() {
    System.out.println(name);
}

public static void main(String[] args) {
    Student s = new Student();
    s.display();
}
Enter fullscreen mode Exit fullscreen mode

}
Output
Arun

In this example, the constructor assigns the value "Arun" to the name variable when the object is created.

Types of Constructors in Java
1. Default Constructor

A constructor that does not take any parameters is called a default constructor.

class Demo {
Demo() {
System.out.println("Default Constructor Called");
}
}
2. Parameterized Constructor

A constructor that accepts parameters is called a parameterized constructor.

class Student {

String name;

Student(String n) {
    name = n;
}

public static void main(String[] args) {
    Student s = new Student("Arun");
    System.out.println(s.name);
}
Enter fullscreen mode Exit fullscreen mode

}
Output
Arun

Parameterized constructors allow different objects to be initialized with different values.

Rules for Creating Constructors

  • Constructor name must be the same as the class name.
  • Constructors do not have a return type.
  • Constructors are called automatically when an object is created.
  • A class can have multiple constructors (Constructor Overloading).

Constructor Overloading Example
class Student {

Student() {
    System.out.println("Default Constructor");
}

Student(String name) {
    System.out.println("Student Name: " + name);
}

public static void main(String[] args) {
    new Student();
    new Student("Arun");
}
Enter fullscreen mode Exit fullscreen mode

}
Output
Default Constructor
Student Name: Arun

Top comments (0)