# Object Lifecycle, Copying and Resources — Object-Oriented Programming (OOP)

Source: https://www.skillbyai.com/en/oop/o-lifecycle

> Understand object creation, garbage collection, copying and resource cleanup.

## From birth to collection

An object is **created** (memory allocated, fields initialised, constructor run), **used** while references to it exist, and becomes **unreachable** when no live references remain. In Java, C#, Python and JavaScript, a **garbage collector** reclaims unreachable objects automatically; you do not free memory manually. C++ instead uses **destructors** and deterministic scope-based cleanup (**RAII**). Because GC timing is unpredictable, do not rely on **finalizers** (deprecated in Java) to release **resources** such as files, sockets and database connections; use **try-with-resources** in Java (with `AutoCloseable`), `using` in C#, or `with` in Python, so cleanup happens at a predictable point. **Copying** objects needs care: a **shallow copy** duplicates the outer object but shares inner objects (both copies point to the same list), while a **deep copy** duplicates the whole structure. Java's `clone()` is widely considered awkward; prefer **copy constructors**, static factory methods, or immutable objects that never need copying.

## Resource cleanup and shallow versus deep copies

try-with-resources closes the reader even if an exception is thrown.

```java
try (var reader = java.nio.file.Files.newBufferedReader(java.nio.file.Path.of("marks.csv"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        process(line);
    }
}   // reader.close() runs here automatically

class Team {
    final String name;
    final List<String> members;

    Team(String name, List<String> members) { this.name = name; this.members = members; }

    Team shallowCopy() { return new Team(name, members); }                    // shares the list
    Team deepCopy()    { return new Team(name, new ArrayList<>(members)); }   // own list
}

// Python equivalents:
// with open("marks.csv") as f: ...
// import copy; copy.copy(obj) (shallow)  /  copy.deepcopy(obj) (deep)
```

## Photocopying a folder

A shallow copy photocopies the folder's cover page that lists the documents inside, so both folders point to the same originals. A deep copy photocopies every document too, so each folder can be changed independently.

**Quiz:** Two Team objects were created by a shallow copy. What happens if one adds a member to its members list?

- [ ] Only that team changes
- [ ] A compile error occurs
- [ ] The garbage collector removes the list
- [x] Both teams see the new member, because they share the same list

*Answer:* Both teams see the new member, because they share the same list. Shallow copies share referenced objects such as the list.
