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
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
Unknown
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
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
//CLUE 2
class Room {
String name;
int area;
// Constructor 1
Room(String name) {
this.name = name;
}
// Constructor 2 (missing)
Room(String name, int area) {
this.name = name;
this.area = area;
// Complete this constructor
// Hint: Use the 'this' keyword
}
}
Room escapeRoom = new Room("Puzzle Room", 500);
System.out.println("Room: " + escapeRoom.name + ", Area: " + escapeRoom.area);
// Should print: Room: Puzzle Room, Area: 500
Room: Puzzle Room, Area: 500
//CLUE 3
class Key {
String keyType;
// Default constructor (to be completed)
Key() {
keyType = "key";
// Hint: Initialize keyType to a default value, e.g., "Unknown"
}
// Parameterized constructor
Key(String keyType) {
this.keyType = keyType;
}
}
Key defaultKey = new Key();
Key customKey = new Key("Golden Key");
System.out.println("Default Key: " + defaultKey.keyType); // Should print: Unknown
System.out.println("Custom Key: " + customKey.keyType); // Should print: Golden Key
Default Key: key
Custom Key: Golden Key
//CLUE 4
class Vault {
String vaultCode;
boolean isLocked;
// Constructor (Fix it)
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);
// Should print: Vault Code: X1Y2Z3, Is Locked: true
Vault Code: X1Y2Z3, Is Locked: true
//CLUE 5
class Safe {
String safeName;
int capacity;
// Default constructor (to be written)
Safe() {
safeName = "Unknown";
capacity = 100;
// Initialize safeName to "Unknown" and capacity to 100
}
// Parameterized constructor (already complete)
Safe(String name, int cap) {
safeName = name;
capacity = cap;
}
}
Safe defaultSafe = new Safe();
Safe customSafe = new Safe("Treasure Safe", 1000);
System.out.println(defaultSafe.safeName + " " + defaultSafe.capacity); // Outputs: Unknown 100
System.out.println(customSafe.safeName + " " + customSafe.capacity); // Outputs: Treasure Safe 1000
Unknown 100
Treasure Safe 1000
//CLUE 6
class Box {
String color;
int weight;
// Constructor (with mistake)
Box(String color, int w) {
this.color = color;
this.weight = w;
}
}
Box myBox = new Box("Red", 50);
System.out.println("Box Color: " + myBox.color + ", Weight: " + myBox.weight);
// Should print: Box Color: Red, Weight: 50
Box Color: Red, Weight: 50
class TreasureChest {
String chestType;
int goldCoins;
boolean isLocked;
// Constructor 1: No parameters (use constructor chaining to call Constructor 2)
TreasureChest() {
// Call Constructor 2 with default values "Wooden", 50, true
this("Wooden", 50, true);
}
// Constructor 2: Takes all parameters
TreasureChest(String type, int coins, boolean locked) {
this.chestType = type;
this.goldCoins = coins;
this.isLocked = locked;
}
// Constructor 3: Takes only type and coins, defaults 'isLocked' to true
TreasureChest(String type, int coins) {
this(type, coins, true); // Call Constructor 2 with true as the 'isLocked' value
}
// Constructor 4: Takes only the number of coins and defaults type to "Wooden" and isLocked to false
TreasureChest(int coins) {
this("Wooden", coins, false); // Call Constructor 2 using "Wooden", coins, and false as values
}
// Print method to check the values
void printChestInfo() {
System.out.println("Chest Type: " + chestType + ", Gold Coins: " + goldCoins + ", Is Locked: " + isLocked);
}
}
//public class EscapeRoom was removed
TreasureChest chest1 = new TreasureChest();
TreasureChest chest2 = new TreasureChest("Golden", 100);
TreasureChest chest3 = new TreasureChest(200);
// Print information to check if everything works correctly
chest1.printChestInfo(); // Should print: Wooden, 50, true
chest2.printChestInfo(); // Should print: Golden, 100, true
chest3.printChestInfo(); // Should print: Wooden, 200, false
if (chest1 != null && chest2 != null && chest3 != null) {
System.out.println("You have successfully escaped!");
}
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.