Java Constructor

In Java, a constructor is a special method that is used to create objects from a class. Constructors have the same name as the class and are used to initialize the state of an object when it is created. They are invoked automatically when an object is created using the new keyword.

Here is an example of a constructor:

public class MyClass {
    private int value;

    public MyClass(int v) {
        value = v;
    }

    public int getValue() {
        return value;
    }
}
Sour‮:ec‬www.theitroad.com

In this example, we have a class called MyClass with a single field value, and a constructor that takes an integer parameter and sets the value of the value field. The constructor has the same name as the class, and takes a single parameter of type int.

To create an object of MyClass, we can use the following code:

MyClass myObj = new MyClass(42);

This will create a new instance of MyClass, with the value field set to 42.

Java also provides a default constructor, which is created automatically if no constructor is defined. The default constructor takes no parameters and does not perform any initialization.

public class MyClass {
    // This class has a default constructor
}

You can also overload constructors, which means you can define multiple constructors with different parameter lists. When you create an object, the appropriate constructor is selected based on the arguments you provide.

public class MyClass {
    private int value;

    public MyClass() {
        value = 0;
    }

    public MyClass(int v) {
        value = v;
    }

    public int getValue() {
        return value;
    }
}

In this example, we have two constructors: one with no parameters, which sets the value to 0, and one that takes an integer parameter and sets the value to that parameter. When you create an object, you can choose which constructor to use based on the arguments you provide:

MyClass obj1 = new MyClass();    // Uses the no-argument constructor
MyClass obj2 = new MyClass(42);  // Uses the constructor that takes an int parameter