Table of Contents
- Introduction
- What is a Constructor?
- Types of Constructors
- Default Constructor
- Parameterized Constructor
- Constructor Overloading
- Purpose of Constructors
- The
this
Keyword- Referring to Instance Variables
- Calling Constructors
- Passing Current Object
- Returning Current Object
- Constructor vs Method
- Common Pitfalls and Best Practices
- Summary
1. Introduction
Constructors are special methods in Java used to initialize objects. When you create a new object using the new
keyword, the constructor of the class is automatically invoked. This module will explore how constructors work, how to overload them, and how the this
keyword enhances clarity and functionality in object-oriented design.
2. What is a Constructor?
A constructor is a block of code that is called when an instance (object) of a class is created. It has the same name as the class and no return type—not even void
.
Basic Syntax:
class MyClass {
MyClass() {
// Constructor code
}
}
Constructors can be used to assign default or user-defined values to instance variables when an object is instantiated.
3. Types of Constructors
a. Default Constructor
If you don’t define any constructor in your class, Java provides a default constructor automatically. This constructor does nothing and is used to create an object without any initial values.
class Book {
String title;
int pages;
}
public class Main {
public static void main(String[] args) {
Book b1 = new Book(); // Implicit default constructor is used
System.out.println(b1.title); // null
System.out.println(b1.pages); // 0
}
}
If you define any constructor yourself, Java no longer provides the default one automatically.
b. Parameterized Constructor
You can define constructors that accept parameters to initialize your object with specific values.
class Book {
String title;
int pages;
Book(String t, int p) {
title = t;
pages = p;
}
}
Now you can create objects with custom values:
Book b = new Book("Effective Java", 416);
c. Constructor Overloading
Constructor overloading allows you to define multiple constructors with different parameter lists within the same class.
class Book {
String title;
int pages;
Book() {
this("Unknown", 0); // Calls another constructor
}
Book(String t) {
this(t, 100); // Default pages if only title is given
}
Book(String t, int p) {
title = t;
pages = p;
}
}
This provides flexibility in object creation and is a powerful example of compile-time polymorphism.
4. Purpose of Constructors
Constructors serve the following main purposes:
- Initialize instance variables
- Allocate system resources, if needed
- Enforce mandatory fields at object creation
- Enhance readability and maintainability by controlling initialization logic
You should use constructors instead of setters if some values are mandatory to create a valid object.
5. The this
Keyword
The this
keyword is a reference to the current object. It’s particularly useful in constructors to distinguish between instance variables and parameters or to invoke another constructor.
a. Referring to Instance Variables
When parameter names shadow instance variables, use this
to resolve ambiguity:
class Book {
String title;
Book(String title) {
this.title = title; // Refers to instance variable
}
}
Without this
, the assignment would be ambiguous and ineffective.
b. Calling Constructors
You can call another constructor from within a constructor using this()
:
class Book {
String title;
int pages;
Book() {
this("Default Title", 100); // Calls another constructor
}
Book(String title, int pages) {
this.title = title;
this.pages = pages;
}
}
this()
must be the first statement in the constructor.
c. Passing Current Object
The current object can be passed as an argument using this
. This is useful in chaining or callback patterns.
class Book {
void print(Book b) {
System.out.println("Title: " + b.title);
}
void display() {
print(this); // Passing current object
}
}
d. Returning Current Object
Methods can also return the current object using this
. This enables method chaining.
class Book {
String title;
Book setTitle(String title) {
this.title = title;
return this;
}
Book print() {
System.out.println(title);
return this;
}
}
new Book().setTitle("Clean Code").print();
6. Constructor vs Method
Feature | Constructor | Method |
---|---|---|
Name | Same as class | Any valid identifier |
Return Type | None (not even void) | Must have a return type |
Invocation | Automatically during object creation | Explicitly using object reference |
Purpose | Initialize object | Perform operations |
Overloading Allowed | Yes | Yes |
Inheritance | Not inherited | Inherited |
7. Common Pitfalls and Best Practices
Pitfalls
- Not using
this
when instance variables are shadowed - Attempting to return a value from a constructor
- Calling
this()
after a statement in a constructor (must be the first line)
Best Practices
- Use
this
only when necessary to reduce verbosity. - Always initialize required fields using constructors.
- Prefer constructor chaining to reduce duplicate code.
- Avoid performing heavy operations in constructors; keep them lightweight.
- Use parameterized constructors for better flexibility and clarity.
8. Summary
In this module, you’ve learned:
- What constructors are and why they are used
- Differences between default, parameterized, and overloaded constructors
- The use of the
this
keyword in accessing variables, calling constructors, and enabling method chaining - How constructors differ from methods
- Best practices for writing clean and efficient constructors
Understanding constructors and the this
keyword lays the foundation for advanced object creation strategies, such as factory methods, builder patterns, and dependency injection.