What is a Constructor in Java?
A constructor in Java is a block of code that initializes an object. It has the same name as the class and does not have a return type (not even void
). Constructors are automatically called when you create an object using the new
keyword.
Key Characteristics of a Constructor
- Name Matches the Class: The constructor name must be the same as the class name.
- No Return Type: Constructors do not return any value, not even
void
. - Automatically Invoked: It gets called automatically when an object is created.
Why Are Constructors Important?
- Initialization: Automatically sets initial values for object attributes.
- Code Reusability: Reduces repetitive code by centralizing the initialization logic.
- Improves Readability: Enhances program clarity by organizing object creation and initialization together.
Syntax of a Constructor
class ClassName {
// Constructor
ClassName() {
// Constructor body
}
}
Types of Constructors in Java
- Default Constructor
- Parameterized Constructor
- Copy Constructor
1. Default Constructor
A default constructor is a no-argument constructor provided by Java if you don’t explicitly define any constructor. It initializes object attributes with default values.
Example: Default Constructor
class Student {
String name;
int age;
// Default Constructor
Student() {
name = "Unknown";
age = 0;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student(); // Calls default constructor
student.display();
}
}
Output:
Name: Unknown, Age: 0
2. Parameterized Constructor
A parameterized constructor accepts parameters to initialize attributes with custom values during object creation.
Example: Parameterized Constructor
class Student {
String name;
int age;
// Parameterized Constructor
Student(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student("Alice", 20); // Pass values to constructor
student.display();
}
}
Output:
Name: Alice, Age: 20
3. Copy Constructor
A copy constructor creates a new object as a copy of an existing object. Java does not provide a built-in copy constructor, but you can create one manually.
Example: Copy Constructor
class Student {
String name;
int age;
// Parameterized Constructor
Student(String name, int age) {
this.name = name;
this.age = age;
}
// Copy Constructor
Student(Student student) {
this.name = student.name;
this.age = student.age;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student student1 = new Student("Bob", 22); // Original object
Student student2 = new Student(student1); // Copy object
student2.display();
}
}
Output:
Name: Bob, Age: 22
Constructor Overloading
Constructor overloading allows a class to have multiple constructors with different parameter lists. This enables flexibility in initializing objects in various ways.
Example: Constructor Overloading
class Employee {
String name;
int salary;
// Default Constructor
Employee() {
name = "Not Assigned";
salary = 0;
}
// Parameterized Constructor
Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
void display() {
System.out.println("Name: " + name + ", Salary: " + salary);
}
}
public class Main {
public static void main(String[] args) {
Employee emp1 = new Employee(); // Calls default constructor
Employee emp2 = new Employee("John", 50000); // Calls parameterized constructor
emp1.display();
emp2.display();
}
}
Output:
Name: Not Assigned, Salary: 0
Name: John, Salary: 50000
Special Keywords in Constructors
- this: Refers to the current object. It is used to distinguish between instance variables and parameters with the same name.
- Example: this.name = name;
- super: Calls the constructor of the parent class in inheritance.
Best Practices for Constructors
- Avoid Long Constructor Parameter Lists: Use objects or builder patterns if many parameters are needed.
- Use Overloading Wisely: Overload constructors to provide multiple ways of initializing objects.
- Initialize All Attributes: Ensure every attribute is initialized to prevent null values or unexpected behavior.
Common Mistakes to Avoid
- Not Defining a Constructor: If you define a parameterized constructor but forget to define a default constructor, it can cause errors.
- Overloading Confusion: Ensure clear and unique parameter lists for overloaded constructors.
Practical Example: Bank Account
class BankAccount {
String accountHolder;
double balance;
// Default Constructor
BankAccount() {
accountHolder = "Unknown";
balance = 0.0;
}
// Parameterized Constructor
BankAccount(String accountHolder, double balance) {
this.accountHolder = accountHolder;
this.balance = balance;
}
void displayDetails() {
System.out.println("Account Holder: " + accountHolder);
System.out.println("Balance: " + balance);
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc1 = new BankAccount(); // Default constructor
BankAccount acc2 = new BankAccount("Alice", 1000.0); // Parameterized constructor
acc1.displayDetails();
acc2.displayDetails();
}
}
Output:
Account Holder: Unknown
Balance: 0.0
Account Holder: Alice
Balance: 1000.0