Commit c58835c
committed
feat: demonstrate core Object class methods (toString, equals, hashCode)
WHAT was implemented:
- Created a `LangDemo` class showcasing the fundamental methods of `Object` class:
- `toString()` → prints the string representation of the object.
- `equals()` → checks object reference equality (when uncommented).
- `hashCode()` → prints a unique hash code for the object.
- Example flow:
1. Created `Object o1` and printed it directly (implicitly calls `toString()`).
2. Printed `o1.toString()` explicitly (same result).
3. Assigned `o2 = o1` to demonstrate reference equality.
4. Printed `o1.hashCode()` to show the hash value assigned by JVM.
WHY this is important:
- All Java classes implicitly extend `Object`, making these methods available everywhere.
- Understanding how `equals`, `hashCode`, and `toString` work is critical for custom classes, especially in collections.
KEY CONCEPTS COVERED:
1. **toString()**
- Default: `ClassName@HexHashCode`.
- Useful for debugging/logging.
- Can be overridden in custom classes for meaningful output.
2. **equals()**
- Default: Compares memory addresses (reference equality).
- Overridable: Custom classes can implement logical equality (e.g., comparing field values).
3. **hashCode()**
- Default: Returns a hash value derived from the object’s memory address.
- Contract: If two objects are equal (`equals()`), they must return the same hash code.
- Essential in hash-based collections (HashMap, HashSet).
4. **Reference Assignment**
- `o2 = o1;` means both variables point to the same object, so `o1.equals(o2)` → true.
REAL-WORLD APPLICATIONS:
- **Custom Classes**: Override `equals()` and `hashCode()` for logical equality (e.g., Employee IDs).
- **Collections**: Hash-based collections rely heavily on these methods for performance and correctness.
- **Logging/Debugging**: Overriding `toString()` provides human-readable representations of objects.
BEST PRACTICES:
- Always override `equals()` and `hashCode()` together when defining logical equality.
- Provide a meaningful `toString()` for debugging (avoid exposing sensitive info).
- Use `Objects.equals()` and `Objects.hash()` (from `java.util.Objects`) for cleaner implementations.
KEYWORDS:
java.lang.Object, toString, equals, hashCode, reference equality, JVM object model.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 11338f6 commit c58835c
1 file changed
+3
-2
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
9 | 9 | | |
10 | 10 | | |
11 | 11 | | |
12 | | - | |
| 12 | + | |
13 | 13 | | |
14 | 14 | | |
15 | | - | |
| 15 | + | |
| 16 | + | |
16 | 17 | | |
17 | 18 | | |
18 | 19 | | |
0 commit comments