Sobes.tech
Intern

What is a constructor in Java?

sobes.tech AI

Answer from AI

This is a special class method used for object initialization. It is called automatically when a new instance of the class is created using the new operator.

Main properties:

  • Has the same name as the class.
  • Does not return any value (even void).
  • Can have parameters used to pass initial values to the object's fields.
  • Can be overloaded (have different numbers or types of parameters).
  • If a constructor is not explicitly declared, the compiler provides a default constructor (a constructor without arguments), which initializes primitive type fields with default values, and reference types with null.

Example:

class MyClass {
    int value;
    String name;

    // Constructor with parameters
    public MyClass(int value, String name) {
        this.value = value;
        this.name = name;
    }

    // Constructor without parameters
    public MyClass() {
        this.value = 0;
        this.name = "Default";
    }
}

// Creating objects
MyClass obj1 = new MyClass(10, "Example"); // Calling constructor with parameters
MyClass obj2 = new MyClass(); // Calling constructor without parameters