What is a constructor in java?
"A constructor in Java is a special 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:
Example
Create a constructor:
// Create a MyClass class
public class MyClass {
int x; // Create a class attribute
// Create a class constructor for the MyClass class
public MyClass() {
x = 5; // Set the initial value for the class attribute x
}
public static void main(String[] args) {
MyClass myObj = new MyClass(); // Create an object of class MyClass (This will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}
// Outputs 5
🔗Reference: stackoverflow.com
🔗Source: Java Interview Questions and Answers