← Back to Week 2 Hub

Object Lifecycle

Watch an object get created, change state through method calls, and see encapsulation in action.

public class Robot { private String name; private int energy; public Robot(String name) { this.name = name; this.energy = 100; } public void work(int hours) { this.energy -= (hours * 15); if (this.energy < 0) this.energy = 0; } public void recharge(int hours) { this.energy += (hours * 20); if (this.energy > 100) this.energy = 100; } public int getEnergy() { return this.energy; } public String getName() { return this.name; } }

Main Method — Step Through

1 Robot bot = new Robot("Atlas"); // Create the object
2 System.out.println(bot.getEnergy()); // Check energy
3 bot.work(3); // Work 3 hours
4 System.out.println(bot.getEnergy()); // Check energy
5 bot.recharge(2); // Recharge 2 hours
6 System.out.println(bot.getEnergy()); // Check energy
7 bot.work(8); // Work 8 hours (heavy!)
8 System.out.println(bot.getEnergy()); // Check energy
Ready to start

Console Output

🤖

No object created yet.

Click Step to create the Robot.

Key Takeaways

📦 Objects hold state (data) that changes over time
🔒 Methods are the only way to change an object's state when fields are private
🚫 No setter for energy — it can only change through work() and recharge()
🛡 This is encapsulation in action: the Robot class controls how energy changes

Step through the code to watch the Robot object come alive and change state.

← Method Overloading Loop Types: while vs do/while vs for →