Java Constructors - hmislk/hmis GitHub Wiki
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:
class Student {
String name;
Student() {
name = "Unknown";
}
}
Creating an object:
Student student = new Student();
When the object is created, Java automatically calls:
Student()
2. Why Do We Need Constructors?
Without constructors, object initialization becomes repetitive.
Example without constructor:
class Student {
String name;
int age;
}
Creating objects:
Student s1 = new Student();
s1.name = "John";
s1.age = 20;
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:
Student s1 = new Student("John",20);
The object is created with valid data immediately.
3. How Object Creation Works in Java
When Java executes:
Student s = new Student();
The JVM performs:
1. Allocate memory for object
↓
2. Initialize variables with default values
↓
3. Execute constructor
↓
4. Return object reference
Example:
class Student {
String name;
int age;
Student(){
name = "Alice";
age = 20;
}
}
Before constructor:
name = null
age = 0
After constructor:
name = Alice
age = 20
4. Constructor Rules
A constructor must follow these rules:
Rule 1: Constructor name must match class name
Correct:
class Student {
Student(){
}
}
Wrong:
class Student {
student(){
}
}
Rule 2: Constructor has no return type
Correct:
Student(){
}
Wrong:
void Student(){
}
The second one is a method, not a constructor.
Rule 3: Constructor is called automatically
You cannot call it like a normal method.
Wrong:
Student();
Correct:
new Student();
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:
class Student {
}
Compiler creates:
Student(){
}
Now:
Student s = new Student();
works correctly.
Important Note
If you create any constructor, Java will not create a default constructor.
Example:
class Student {
Student(String name){
}
}
Now:
Student s = new Student();
causes:
Compile Error
7. No-Argument Constructor
A no-argument constructor is a constructor without parameters.
Example:
class Student {
String name;
Student(){
name = "Unknown";
}
}
Usage:
Student s = new Student();
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:
Student s = new Student("John",21);
Object state:
name = John
age = 21
9. Constructor Overloading
Constructor overloading means having multiple constructors with different parameters.
Example:
class Student {
Student(){
}
Student(String name){
}
Student(String name, int age){
}
}
Java decides which constructor to call based on arguments.
Example:
new Student();
new Student("John");
new Student("John",20);
10. Using this Keyword in Constructors
this refers to the current object.
It is commonly used to differentiate instance variables and constructor parameters.
Example:
class Student {
String name;
Student(String name){
this.name = name;
}
}
Without this:
name = name;
Both refer to the parameter.
With this:
this.name
means object variable.
11. Constructor Chaining
Constructor chaining means calling one constructor from another constructor.
It avoids duplicate code.
Example:
class Student {
Student(){
this("Unknown");
}
Student(String name){
System.out.println(name);
}
}
Execution:
Student()
↓
Student(String)
↓
Print name
Rules of this()
- Must be the first statement.
- Can only call another constructor in the same class.
- Cannot call multiple constructors.
Example:
Student(){
this("John");
System.out.println("Hello");
}
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:
Animal Constructor
Dog Constructor
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:
new C();
Output:
A
B
C
Order:
Parent
↓
Child
↓
Grand Child
14. Constructors and Inheritance
Constructors are not inherited.
Example:
class Parent {
Parent(){
}
}
class Child extends Parent {
}
Child does not inherit the constructor.
Instead, Java automatically calls:
super();
15. Constructor Access Modifiers
Constructors can have access modifiers.
Public Constructor
Accessible everywhere.
public Student(){
}
Protected Constructor
Accessible in subclasses and same package.
protected Student(){
}
Package Private Constructor
No modifier.
Student(){
}
Private Constructor
Accessible only inside the class.
private Student(){
}
16. Private Constructors
Private constructors prevent object creation from outside the class.
Common uses:
- Singleton Pattern
- Utility Classes
- Factory Pattern
Example:
class Database {
private Database(){
}
}
Now:
new Database();
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:
Student s1 = new Student("John");
Student s2 = new Student(s1);
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:
Initialization Block
↓
Constructor
20. Common Constructor Mistakes
Mistake 1: Adding return type
Wrong:
void Student(){
}
Correct:
Student(){
}
Mistake 2: Wrong class name
Wrong:
student(){
}
Correct:
Student(){
}
Mistake 3: Forgetting constructor chaining rules
Wrong:
Student(){
System.out.println("Hello");
this("John");
}
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:
Student(String name){
this.name=name;
}
2. Use constructor validation
Example:
Student(int age){
if(age < 0){
throw new IllegalArgumentException();
}
}
3. Keep constructors simple
Avoid:
- Database calls
- Network calls
- Heavy calculations
4. Use final fields where possible
Example:
class Student {
private final int id;
Student(int id){
this.id=id;
}
}
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.