Initiative: To master the this reference for scope resolution and track memory references.
public class MemoryTracker { // Define class to track object memory and reference scope
private String tag; // Declare instance variable to label the specific object
private static int total = 0; // Declare shared static variable to count total instances
public MemoryTracker(String tag) { // Constructor accepting a tag string
this.tag = tag; // Use 'this' to distinguish the field from the local parameter
total++; // Increment the global counter shared by all objects
System.out.println("New object tagged: " + this.tag); // Log the creation with its tag
} // End of constructor
public void printDetails() { // Instance method to show identity and memory info
System.out.println("Tag: " + this.tag); // Access the current object's tag using 'this'
System.out.println("Hash: " + this.hashCode()); // Print the unique hashcode (memory reference)
System.out.println("Global Count: " + total); // Print the static shared count
} // End of printDetails method
public MemoryTracker chainUpdate(String newTag) { // Method demonstrating 'this' for method chaining
this.tag = newTag; // Update the object's tag field
return this; // Return the current object instance back to the caller
} // End of chainUpdate method
public static void main(String[] args) { // Entry point for memory tracking demonstration
System.out.println("--- Memory Reference Lab ---"); // Print lab header
MemoryTracker m1 = new MemoryTracker("Alpha"); // Create the first memory tracker object
m1.printDetails(); // Show details for Alpha object
System.out.println("---------------------------"); // Print separator
MemoryTracker m2 = new MemoryTracker("Beta"); // Create the second memory tracker object
m2.chainUpdate("Beta-V2").printDetails(); // Update tag and print details using chaining
System.out.println("---------------------------"); // Print separator
MemoryTracker m3 = new MemoryTracker("Gamma"); // Create the third memory tracker object
m3.printDetails(); // Show details for Gamma object
System.out.println("Total Objects Tracked: " + MemoryTracker.total); // Final count of all instances
} // End of main method
} // End of MemoryTracker class