Constructors
How objects are born.
Constructors
Analogy: factory
A Constructor is like a Factory Assembly Line.
When you order a car, you specify the color, engine, and wheels. The factory (Constructor) takes these specifications and builds the car exactly how you want it.
You can't drive the car until it's fully built!
The Robot Assembly Line
Imagine you are building a robot. You can choose which parts to include.
- Pass
truefor Head, Body, etc. - The Constructor takes these parts and assembles the robot.
Robot Assembly Line (Constructors)
Select Parts (Parameters)
Code:
new Robot(...);
Ready to build.
The Code
A constructor has the same name as the class and no return type.
Java Example
Switch language in Navbar
class Robot {
boolean hasHead;
boolean hasBody;
// The Constructor
Robot(boolean head, boolean body) {
this.hasHead = head;
this.hasBody = body;
System.out.println("Robot Built!");
}
}
Calling the constructor:
Java Example
Switch language in Navbar
// Calls the constructor with arguments
Robot myBot = new Robot(true, true);
Advanced Concepts
1. Destructors
If a Constructor is "Birth", a Destructor is "Death". It runs when an object is destroyed (e.g., when it goes out of scope) to clean up memory.
- Java: Uses Garbage Collection, so no explicit destructors (but has
finalize(), which is deprecated). - C++: Uses
~ClassName()to manually clean up.
Java Example
Switch language in Navbar
// Java uses Garbage Collection (GC)
// No explicit destructor needed.
// The GC cleans up memory automatically when objects are no longer used.
2. Copy Constructors
What if you want to clone a robot? A Copy Constructor creates a new object by copying an existing one.
Java Example
Switch language in Navbar
class Robot {
String name;
// Normal Constructor
Robot(String name) { this.name = name; }
// Copy Constructor
Robot(Robot other) {
this.name = other.name; // Copy data from the other robot
}
}
Robot bot1 = new Robot("R2D2");
Robot bot2 = new Robot(bot1); // bot2 is a copy of bot1
Up Next
Static Keyword