Constructor in Java

Definition:

A constructor in Java is a special type of method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes.

Characteristics of Constructors:

  1. Name: The name of the constructor must be the same as the name of the class.
  2. No Return Type: Constructors do not have a return type, not even void.
  3. Invocation: Constructors are automatically called when an object is created.
  4. Overloading: Constructors can be overloaded, meaning you can have more than one constructor in a class with different parameter lists.

Types of Constructors:

  1. Default Constructor
  2. Parameterized Constructor
  3. No-Argument Constructor
  4. Copy Constructor (not natively supported in Java but can be implemented manually)

Default Constructor:

A default constructor is automatically provided by the Java compiler if no constructor is explicitly defined. It initializes the object with default values (zero, null, etc.).

class Example {
    // Default constructor
    Example() {
        System.out.println("Default Constructor Called");
    }
}

public class Main {
    public static void main(String[] args) {
        Example obj = new Example(); // Default constructor is called
    }
}

Parameterized Constructor:

A parameterized constructor is defined with parameters, allowing you to initialize an object with specific values when it is created.

class Example {
    int x;

    // Parameterized constructor
    Example(int x) {
        this.x = x;
        System.out.println("Parameterized Constructor Called with value: " + x);
    }
}

public class Main {
    public static void main(String[] args) {
        Example obj = new Example(10); // Parameterized constructor is called
    }
}

No-Argument Constructor: