# Java Constructors > A complete guide to understanding Java constructors from beginner to advanced level. --- # Table of Contents 1. What is a Constructor? 2. Why Do We Need Constructors? 3. How Object Creation Works in Java 4. Constructor Rules 5. Types of Constructors 6. Default Constructor 7. No-Argument Constructor 8. Parameterized Constructor 9. Constructor Overloading 10. Using `this` Keyword in Constructors 11. Constructor Chaining 12. Using `super()` in Constructors 13. Constructor Execution Order 14. Constructors and Inheritance 15. Constructor Access Modifiers 16. Private Constructors 17. Copy Constructor in Java 18. Constructor vs Method 19. Initialization Blocks vs Constructors 20. Common Constructor Mistakes 21. Best Practices 22. Real-World Examples 23. Interview Questions 24. 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: ```java class Student { String name; Student() { name = "Unknown"; } } ``` Creating an object: ```java Student student = new Student(); ``` When the object is created, Java automatically calls: ```java Student() ``` --- # 2. Why Do We Need Constructors? Without constructors, object initialization becomes repetitive. Example without constructor: ```java class Student { String name; int age; } ``` Creating objects: ```java Student s1 = new Student(); s1.name = "John"; s1.age = 20; ``` Every object requires manual initialization. With a constructor: ```java class Student { String name; int age; Student(String name, int age){ this.name = name; this.age = age; } } ``` Now: ```java Student s1 = new Student("John",20); ``` The object is created with valid data immediately. --- # 3. How Object Creation Works in Java When Java executes: ```java 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: ```java 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: ```java class Student { Student(){ } } ``` Wrong: ```java class Student { student(){ } } ``` --- ## Rule 2: Constructor has no return type Correct: ```java Student(){ } ``` Wrong: ```java 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: ```java Student(); ``` Correct: ```java 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: ```java class Student { } ``` Compiler creates: ```java Student(){ } ``` Now: ```java Student s = new Student(); ``` works correctly. --- ## Important Note If you create any constructor, Java will not create a default constructor. Example: ```java class Student { Student(String name){ } } ``` Now: ```java Student s = new Student(); ``` causes: ``` Compile Error ``` --- # 7. No-Argument Constructor A no-argument constructor is a constructor without parameters. Example: ```java class Student { String name; Student(){ name = "Unknown"; } } ``` Usage: ```java Student s = new Student(); ``` --- # 8. Parameterized Constructor A parameterized constructor accepts values. Example: ```java class Student { String name; int age; Student(String name, int age){ this.name = name; this.age = age; } } ``` Usage: ```java 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: ```java class Student { Student(){ } Student(String name){ } Student(String name, int age){ } } ``` Java decides which constructor to call based on arguments. Example: ```java 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: ```java class Student { String name; Student(String name){ this.name = name; } } ``` Without `this`: ```java name = name; ``` Both refer to the parameter. With `this`: ```java this.name ``` means object variable. --- # 11. Constructor Chaining Constructor chaining means calling one constructor from another constructor. It avoids duplicate code. Example: ```java 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: ```java Student(){ this("John"); System.out.println("Hello"); } ``` Valid. --- # 12. Using `super()` in Constructors `super()` calls the parent class constructor. Example: ```java 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: ```java 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: ```java new C(); ``` Output: ``` A B C ``` Order: ``` Parent ↓ Child ↓ Grand Child ``` --- # 14. Constructors and Inheritance Constructors are not inherited. Example: ```java class Parent { Parent(){ } } class Child extends Parent { } ``` Child does not inherit the constructor. Instead, Java automatically calls: ```java super(); ``` --- # 15. Constructor Access Modifiers Constructors can have access modifiers. ## Public Constructor Accessible everywhere. ```java public Student(){ } ``` --- ## Protected Constructor Accessible in subclasses and same package. ```java protected Student(){ } ``` --- ## Package Private Constructor No modifier. ```java Student(){ } ``` --- ## Private Constructor Accessible only inside the class. ```java private Student(){ } ``` --- # 16. Private Constructors Private constructors prevent object creation from outside the class. Common uses: - Singleton Pattern - Utility Classes - Factory Pattern Example: ```java class Database { private Database(){ } } ``` Now: ```java new Database(); ``` is impossible. --- # Singleton Example ```java 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: ```java class Student { String name; Student(String name){ this.name = name; } Student(Student other){ this.name = other.name; } } ``` Usage: ```java 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: ```java 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: ```java void Student(){ } ``` Correct: ```java Student(){ } ``` --- ## Mistake 2: Wrong class name Wrong: ```java student(){ } ``` Correct: ```java Student(){ } ``` --- ## Mistake 3: Forgetting constructor chaining rules Wrong: ```java 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: ```java Student(String name){ this.name=name; } ``` --- ## 2. Use constructor validation Example: ```java 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: ```java class Student { private final int id; Student(int id){ this.id=id; } } ``` --- # 22. Real-World Examples ## User Class ```java class User { private String username; private String email; User(String username,String email){ this.username=username; this.email=email; } } ``` --- ## Bank Account ```java class BankAccount { private String accountNumber; private double balance; BankAccount(String accountNumber,double balance){ this.accountNumber = accountNumber; this.balance = balance; } } ``` --- ## Product Class ```java 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.