Constructors in Java

java dev.to

What is a Constructor?

A Constructor is a special method in Java that is automatically called when an object is created.

It is used to initialize object values.

Key Features of Constructor:

Constructor name must be the same as the class name.

Constructor does not have a return type (not even void).

Constructor is called automatically when an object is created.

Used to initialize object data.

Syntax:

class ClassName {

    ClassName() {
        // Constructor body
    }
}
Enter fullscreen mode Exit fullscreen mode

Example:

public class Student {

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

    public static void main(String[] args) {

        Student s1 = new Student();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Constructor Called
Enter fullscreen mode Exit fullscreen mode

How it Works?

Student s1 = new Student();

Constructor is called automatically

Output: Constructor Called.

Why Do We Use Constructors?

To initialize object values.
To reduce repetitive code.
To set default values when an object is created.
To make object creation easier.

Types of Constructors:

  1. Default Constructor:
class Student {

    Student() {
        System.out.println("Default Constructor");
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Parameterized Constructor:
class Student {

    String name;

    Student(String name) {
        this.name = name;
    }

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

    public static void main(String[] args) {

        Student s1 = new Student("Bala");
        s1.display();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Bala
Enter fullscreen mode Exit fullscreen mode

Source: dev.to

arrow_back Back to Tutorials