In Java, a constructor is a special block of code used to initialize objects upon instantiation. Its automatically invoked when the new keyword is used to create an instance. Unlike regular methods, constructors do not have a return type—not even void—and share the exact name of their enclosing class.
The primary purpose of a constructor is to set initial values for instance fields and perform any setup required for proper object initialization.
Constructor Declaration Rules
- The constructor’s name must match the class name exactly.
- Constructors must not declare a return type (not even
void).
Differences Between Constructors and Regular Methods
- Constructors execute automatically upon object creation and are called only once per instance.
- Regular methods are invoked explicitly via the dot operator (e.g.,
obj.method()) and may be called multiple times after the object exists.
Example: Constructor Usage
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// Default constructor—if none are explicitly defined, the compiler provides one
// Person() { }
// Parameterized constructor
Person(String name, int age) {
this.name = name;
this.age = age;
}
public static void main(String[] args) {
Person p1 = new Person("Alice", 25);
Person p2 = new Person("Bob", 30);
System.out.println("Person 1: " + p1.getName() + " (" + p1.getAge() + ")");
System.out.println("Person 2: " + p2.getName() + " (" + p2.getAge() + ")");
}
}
</div>### Static Members in Java
A **static method** belongs to the class itself rather than to any instance of the class. It is declared using the `static` keyword and can be invoked using the class name (e.g., `ClassName.method()`), without requiring object instantiation.
Static methods are commonly used in utility classes where functionality does not depend on instance-specific state. A well-known example is `Integer.parseInt(String)`, which converts a string to an integer.
<div class="warning note">**Note:** Static methods cannot access instance variables or instance methods directly; they are restricted to static members only.</div>#### Example: Static vs. Instance Methods
<div class="code-block">```
class Utility {
// Instance method
void displayInstanceMessage() {
System.out.println("Called on an object instance.");
}
// Static method
static void displayStaticMessage() {
System.out.println("Called on the class directly.");
}
public static void main(String[] args) {
// Calling static method without object
Utility.displayStaticMessage();
// Calling instance method via object
Utility util = new Utility();
util.displayInstanceMessage();
}
}