Java Constructors¶
A complete guide to understanding Java constructors from beginner to advanced level.
Table of Contents¶
- What is a Constructor?
- Why Do We Need Constructors?
- How Object Creation Works in Java
- Constructor Rules
- Types of Constructors
- Default Constructor
- No-Argument Constructor
- Parameterized Constructor
- Constructor Overloading
- Using
thisKeyword in Constructors - Constructor Chaining
- Using
super()in Constructors - Constructor Execution Order
- Constructors and Inheritance
- Constructor Access Modifiers
- Private Constructors
- Copy Constructor in Java
- Constructor vs Method
- Initialization Blocks vs Constructors
- Common Constructor Mistakes
- Best Practices
- Real-World Examples
- Interview Questions
- Final Summary
1. What is a Constructor?¶
A constructor is a special member of a class that is used to initialize objects.
A constructor is automatically executed when an object is created using the new keyword.
Example:
Creating an object:
When the object is created, Java automatically calls:
2. Why Do We Need Constructors?¶
Without constructors, object initialization becomes repetitive.
Example without constructor:
Creating objects:
Every object requires manual initialization.
With a constructor:
class Student {
String name;
int age;
Student(String name, int age){
this.name = name;
this.age = age;
}
}
Now:
The object is created with valid data immediately.
3. How Object Creation Works in Java¶
When Java executes:
The JVM performs:
1. Allocate memory for object
↓
2. Initialize variables with default values
↓
3. Execute constructor
↓
4. Return object reference
Example:
Before constructor:
After constructor:
4. Constructor Rules¶
A constructor must follow these rules:
Rule 1: Constructor name must match class name¶
Correct:
Wrong:
Rule 2: Constructor has no return type¶
Correct:
Wrong:
The second one is a method, not a constructor.
Rule 3: Constructor is called automatically¶
You cannot call it like a normal method.
Wrong:
Correct:
Rule 4: Constructors can be overloaded¶
A class can have multiple constructors.
Rule 5: Constructors cannot be overridden¶
Constructors belong to object creation, not inheritance.
5. Types of Constructors¶
Java has three commonly used constructor types:
| Type | Description |
|---|---|
| Default Constructor | Created automatically by compiler |
| No-Argument Constructor | Programmer-created constructor without parameters |
| Parameterized Constructor | Constructor that accepts values |
6. Default Constructor¶
A default constructor is automatically created by Java if no constructor is written.
Example:
Compiler creates:
Now:
works correctly.
Important Note¶
If you create any constructor, Java will not create a default constructor.
Example:
Now:
causes:
7. No-Argument Constructor¶
A no-argument constructor is a constructor without parameters.
Example:
Usage:
8. Parameterized Constructor¶
A parameterized constructor accepts values.
Example:
class Student {
String name;
int age;
Student(String name, int age){
this.name = name;
this.age = age;
}
}
Usage:
Object state:
9. Constructor Overloading¶
Constructor overloading means having multiple constructors with different parameters.
Example:
Java decides which constructor to call based on arguments.
Example:
10. Using this Keyword in Constructors¶
this refers to the current object.
It is commonly used to differentiate instance variables and constructor parameters.
Example:
Without this:
Both refer to the parameter.
With this:
means object variable.
11. Constructor Chaining¶
Constructor chaining means calling one constructor from another constructor.
It avoids duplicate code.
Example:
Execution:
Rules of this()¶
- Must be the first statement.
- Can only call another constructor in the same class.
- Cannot call multiple constructors.
Example:
Valid.
12. Using super() in Constructors¶
super() calls the parent class constructor.
Example:
class Animal {
Animal(){
System.out.println("Animal Constructor");
}
}
class Dog extends Animal {
Dog(){
super();
System.out.println("Dog Constructor");
}
}
Output:
13. Constructor Execution Order¶
In inheritance, parent constructors execute before child constructors.
Example:
class A {
A(){
System.out.println("A");
}
}
class B extends A {
B(){
System.out.println("B");
}
}
class C extends B {
C(){
System.out.println("C");
}
}
Creating:
Output:
Order:
14. Constructors and Inheritance¶
Constructors are not inherited.
Example:
Child does not inherit the constructor.
Instead, Java automatically calls:
15. Constructor Access Modifiers¶
Constructors can have access modifiers.
Public Constructor¶
Accessible everywhere.
Protected Constructor¶
Accessible in subclasses and same package.
Package Private Constructor¶
No modifier.
Private Constructor¶
Accessible only inside the class.
16. Private Constructors¶
Private constructors prevent object creation from outside the class.
Common uses:
- Singleton Pattern
- Utility Classes
- Factory Pattern
Example:
Now:
is impossible.
Singleton Example¶
class Database {
private static Database instance;
private Database(){
}
public static Database getInstance(){
if(instance == null){
instance = new Database();
}
return instance;
}
}
Only one object can exist.
17. Copy Constructor in Java¶
Java does not provide built-in copy constructors.
But we can create our own.
Example:
class Student {
String name;
Student(String name){
this.name = name;
}
Student(Student other){
this.name = other.name;
}
}
Usage:
18. Constructor vs Method¶
| Constructor | Method |
|---|---|
| Initializes objects | Performs operations |
| Same name as class | Any valid name |
| No return type | Has return type |
| Called automatically | Called manually |
| Cannot be overridden | Can be overridden |
| Runs during object creation | Runs when called |
19. Initialization Blocks vs Constructors¶
Java initialization block:
class Student {
{
System.out.println("Initialization Block");
}
Student(){
System.out.println("Constructor");
}
}
Execution:
20. Common Constructor Mistakes¶
Mistake 1: Adding return type¶
Wrong:
Correct:
Mistake 2: Wrong class name¶
Wrong:
Correct:
Mistake 3: Forgetting constructor chaining rules¶
Wrong:
this() must be the first statement.
Mistake 4: Creating unnecessary constructors¶
Too many constructors make classes difficult to maintain.
21. Best Practices¶
1. Initialize required fields in constructors¶
Good:
2. Use constructor validation¶
Example:
3. Keep constructors simple¶
Avoid:
- Database calls
- Network calls
- Heavy calculations
4. Use final fields where possible¶
Example:
22. Real-World Examples¶
User Class¶
class User {
private String username;
private String email;
User(String username,String email){
this.username=username;
this.email=email;
}
}
Bank Account¶
class BankAccount {
private String accountNumber;
private double balance;
BankAccount(String accountNumber,double balance){
this.accountNumber = accountNumber;
this.balance = balance;
}
}
Product Class¶
class Product {
String name;
double price;
Product(String name,double price){
this.name=name;
this.price=price;
}
}
23. Final Summary¶
| Concept | Description |
|---|---|
| Constructor | Initializes objects |
| Same name as class | Required |
| Return type | Not allowed |
| Called automatically | Yes |
| Default constructor | Compiler generated |
| Parameterized constructor | Initializes with values |
| Overloading | Multiple constructors |
this() |
Calls another constructor |
super() |
Calls parent constructor |
| Inherited | No |
| Overridden | No |
| Private constructors | Used for Singleton and utility classes |
| Best practice | Keep constructors simple |
Final Takeaways¶
- Constructors are responsible for creating valid objects.
- Every Java object creation involves constructor execution.
- Use parameterized constructors to initialize required values.
- Use
this()for constructor reuse inside a class. - Use
super()when working with inheritance. - Constructors are not methods and follow different rules.
- Good constructor design improves code readability, safety, and maintainability.