When you create a new object with new Car(), you often want the object to be immediately initialized with valid data. You don't want to rely on the programmer remembering to manually set every field after creation. Constructors solve this problem.
A Constructor is a special method that is automatically called at the moment an object is instantiated. Its primary purpose is to initialize the object's attributes.
void).new keyword; you never call them directly.class Student {
String name;
int age;
// Constructor
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
// Usage
Student s = new Student("Alice", 20);
// name and age are immediately initialized. No manual setup needed.
If you do not write any constructor in your class, the compiler automatically provides a no-argument Default Constructor that initializes all attributes to their default values (0, null, false).
However, the moment you write any custom constructor, the compiler stops providing the default one. If you still want a no-argument constructor, you must explicitly write one yourself.
A constructor that accepts arguments to initialize the object with specific values.
Student(String name, int age) {
this.name = name;
this.age = age;
}
A constructor that creates a new object as a copy of an existing object. While C++ has a formal copy constructor mechanism, Java does not have one built-in; you must implement it manually.
// Copy constructor in Java
Student(Student other) {
this.name = other.name;
this.age = other.age;
}
A class can have multiple constructors with different parameter lists. This is called Constructor Overloading. The compiler determines which constructor to call based on the number and types of arguments passed.
class Student {
String name;
int age;
Student() {
this.name = "Unknown";
this.age = 0;
}
Student(String name) {
this.name = name;
this.age = 18; // default age
}
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
A Destructor is a special method called when an object is being destroyed to release resources (like closing file handles, freeing network connections, or deallocating memory).
C++ provides explicit destructors using the tilde (~) syntax. They are called automatically when an object goes out of scope or is explicitly deleted.
class FileHandler {
public:
~FileHandler() {
// Close the file handle
fclose(this->filePtr);
}
};
Java does not have destructors. Instead, the Garbage Collector (GC) automatically reclaims memory from objects that are no longer referenced by any variable. The GC runs in the background as a daemon thread, and the programmer has no direct control over when (or if) an object's memory will be freed.
Java previously had a finalize() method, but it was officially deprecated due to unreliable behavior and severe performance penalties.