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.
void.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
}
}
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
}
}