A constructor in Java is a block of code similar to a method that’s called when an instance of an object is created.
Source Code
public class MyClass {
int x;
public MyClass(int y) {
x = y;
}
public static void main(String[] args) {
MyClass myObj = new MyClass(5);
System.out.println(myObj.x); // Outputs 5
}
}
Constructors initialize new objects and can take parameters to set initial values for the object’s attributes.