Introduction to Constructors in Java

What are Constructors?

In Java, a constructor is a special method used to initialize objects. The constructor is called when an object of a class is created. It has the same name as the class and does not return any value, not even void.

Key Points:

  • Same name as class: The constructor must have the same name as the class.
  • No return type: Constructors do not return any value.
  • Used to initialize objects: They set initial values for object attributes.

Types of Constructors

TypesofConstructors

1. Default Constructor:

A constructor that does not accept any parameters. Java provides a default constructor if you don’t define any.

class Car {
    String brand;
    
    // Default constructor
    Car() {
        brand = "Unknown";
    }
}

Car myCar = new Car();
System.out.println(myCar.brand);  // Outputs: Unknown
null

2. Parameterized Constructor:

A constructor that takes parameters to initialize object attributes with custom values.

class Car {
    String brand;

    // Parameterized constructor
    Car(String b) {
        brand = b;
    }
}

Car myCar = new Car("Toyota");
System.out.println(myCar.brand);  // Outputs: Toyota
Toyota

3. Constructor Overloading

Constructor Overloading

In Java, you can have more than one constructor in a class. This is known as constructor overloading. Each constructor must have a different parameter list.

class Car {
    String brand;
    int year;

    // Default constructor
    Car() {
        brand = "Unknown";
        year = 0;
    }

    // Parameterized constructor
    Car(String b, int y) {
        brand = b;
        year = y;
    }
}
Car car1 = new Car();
Car car2 = new Car("Ford", 2020);
System.out.println(car1.brand + " " + car1.year);  // Outputs: Unknown 0
System.out.println(car2.brand + " " + car2.year);  // Outputs: Ford 2020
Unknown 0
Ford 2020

Constructors Diagram

Escape Room: Constructor Puzzle

You’re trapped in a room and the only way out is to unlock a door using your Java constructor knowledge!

Rules:

  • Each clue is a code snippet related to constructors. Solve the problems to reveal the next clue.
  • Once you complete all tasks, you will receive the “escape” message.

Clue 1:

The constructor below is missing a key part. Complete the code so that it runs correctly.

// CLUE  1 

class Door {
    String lockCode;

    // Add the correct constructor here
    Door(String lock) {
        // Constructor body
        lockCode = lock;
    }
}


Door escapeDoor = new Door("1234");
System.out.println(escapeDoor.lockCode);  // Should print: 1234

1234

public class Room {
    String name;
    int area;


    Room(String name) {
        this.name = name;
    }


    Room(String name, int area) {
        this.name = name;
        this.area = area;  
    }
}

Room escapeRoom = new Room("Puzzle Room", 500);

System.out.println("Room: " + escapeRoom.name + ", Area: " + escapeRoom.area);  
Room: Puzzle Room, Area: 500
class Key {
    String keyType;

    
    Key() {
        this.keyType = "Unknown"; 
    }

   
    Key(String keyType) {
        this.keyType = keyType;
    }
}

Key defaultKey = new Key();
Key customKey = new Key("Golden Key");

// Print the key types
System.out.println("Default Key: " + defaultKey.keyType);  
System.out.println("Custom Key: " + customKey.keyType);    
Default Key: Unknown
Custom Key: Golden Key
class Vault {
    String vaultCode;
    boolean isLocked;

    
    Vault(String code, boolean lockStatus) {
        this.vaultCode = code;
        this.isLocked = lockStatus;
    }
}


Vault secretVault = new Vault("X1Y2Z3", true);


System.out.println("Vault Code: " + secretVault.vaultCode + ", Is Locked: " + secretVault.isLocked);  

Vault Code: X1Y2Z3, Is Locked: true
class Safe {
    String safeName;
    int capacity;


    Safe() {
        this.safeName = "Unknown";
        this.capacity = 100;
    }


    Safe(String name, int cap) {
        this.safeName = name;
        this.capacity = cap;
    }
}

Safe defaultSafe = new Safe();
Safe customSafe = new Safe("Treasure Safe", 1000);

System.out.println(defaultSafe.safeName + " " + defaultSafe.capacity); 
System.out.println(customSafe.safeName + " " + customSafe.capacity);    
Unknown 100
Treasure Safe 1000
class Box {
    String color;
    int weight;

    Box(String color, int weight) {
        this.color = color;
        this.weight = weight;  
    }
}


Box myBox = new Box("Red", 50);


System.out.println("Box Color: " + myBox.color + ", Weight: " + myBox.weight);

Box Color: Red, Weight: 50

class TreasureChest {
    String chestType;
    int goldCoins;
    boolean isLocked;

    TreasureChest() {
        this("Wooden", 50, true); 
    }

    TreasureChest(String type, int coins, boolean locked) {
        chestType = type;
        goldCoins = coins;
        isLocked = locked;
    }

    TreasureChest(String type, int coins) {
        this(type, coins, true);  
    }

   
    TreasureChest(int coins) {
        this("Wooden", coins, false);  
    }

    void printChestInfo() {
        System.out.println("Chest Type: " + chestType + ", Gold Coins: " + goldCoins + ", Is Locked: " + isLocked);
    }
}

public class EscapeRoom {
    public static void main(String[] args) {
        TreasureChest chest1 = new TreasureChest();             
        TreasureChest chest2 = new TreasureChest("Golden", 100);  
        TreasureChest chest3 = new TreasureChest(200);           

        chest1.printChestInfo();  
        chest2.printChestInfo();  
        chest3.printChestInfo(); 

        if (chest1 != null && chest2 != null && chest3 != null) {
            System.out.println("You have successfully escaped!");
        }
    }
}

EscapeRoom.main(null);
Chest Type: Wooden, Gold Coins: 50, Is Locked: true
Chest Type: Golden, Gold Coins: 100, Is Locked: true
Chest Type: Wooden, Gold Coins: 200, Is Locked: false
You have successfully escaped!

HINT:

1. Constructor chaining: You must properly use this() to chain constructors and avoid code duplication.
2.	Calling another constructor from a constructor: Ensure that each constructor calls the correct constructor with default or passed values.
3.	Initialize all fields properly: Ensure that every TreasureChest object is initialized with the correct values based on the constructor called.