In Java, a constructor is a special type of method that is used to initialize objects. The constructor is called when an object of a class is created, and it can set initial values for the object’s attributes. A constructor has the same name as the class and does not have a return type.
Java supports different types of constructors:
A default constructor is automatically generated by the Java compiler if no constructor is explicitly defined in the class. It initializes the object with default values (e.g., null
for objects, 0
for integers, false
for booleans).
public class Example {
// Default constructor
public Example() {
System.out.println("Default constructor called");
}
}
A parameterized constructor allows you to initialize an object with specific values when it is created. This is useful when you want to set different initial values for different objects.
public class Example {
private int value;
// Parameterized constructor
public Example(int value) {
this.value = value;
System.out.println("Parameterized constructor called with value: " + value);
}
}
A copy constructor is used to create a new object as a copy of an existing object. Although Java does not provide a built-in copy constructor, you can define one in your class.
public class Example {
private int value;
// Parameterized constructor
public Example(int value) {
this.value = value;
}
// Copy constructor
public Example(Example other) {
this.value = other.value;
System.out.println("Copy constructor called");
}
}
Java allows constructor overloading, which means you can define multiple constructors in a class with different parameter lists. The correct constructor is called based on the arguments passed during object creation.
public class Example {
private int value;
private String name;
// Default constructor
public Example() {
this.value = 0;
this.name = "Default";
}
// Parameterized constructor
public Example(int value) {
this.value = value;
this.name = "Default";
}
// Another parameterized constructor
public Example(int value, String name) {
this.value = value;
this.name = name;
}
}
this
keyword can be used to refer to the current object instance.