0
0
Javaprogramming~15 mins

Object lifetime in Java - Mini Project: Build & Apply

Choose your learning style8 modes available
folder_codeObject lifetime
📖 Scenario: Imagine you are managing a small library system. Each book is represented as an object. You want to understand when these book objects are created and when they are no longer needed (destroyed).
🎯 Goal: You will create a simple Java program that shows the creation and destruction of book objects by printing messages when objects are created and when they are about to be destroyed by the garbage collector.
📋 What You'll Learn
Create a Book class with a constructor that prints a creation message
Override the finalize() method in Book to print a destruction message
Create multiple Book objects in the main method
Remove references to some Book objects and call the garbage collector
Print messages to observe object lifetime
💡 Why This Matters
🌍 Real World
Understanding object lifetime helps manage memory in programs and avoid memory leaks.
💼 Career
Java developers must know how objects are created and cleaned up to write efficient and reliable applications.
Progress0 / 4 steps
1
Create the Book class with constructor
Create a class called Book with a constructor that prints "Book created" when a new object is made.
Java
💡 Need a hint?

The constructor has the same name as the class and no return type.

2
Add finalize method to Book class
Inside the Book class, add a protected void finalize() method that prints "Book destroyed" when the object is about to be removed by the garbage collector.
Java
💡 Need a hint?

Use @Override annotation and call super.finalize() inside the method.

3
Create Book objects and remove references
In the main method, create three Book objects named b1, b2, and b3. Then set b2 and b3 to null to remove their references.
Java
💡 Need a hint?

Remember to declare variables with the type Book and assign new objects using new Book().

4
Call garbage collector and print message
After setting b2 and b3 to null, call System.gc() to suggest garbage collection. Then print "Garbage collector called" to observe the output.
Java
💡 Need a hint?

Use System.gc() to suggest garbage collection and System.out.println() to print the message.