Commit b900137
committed
feat(generics): add GenericClass2 with multiple type parameters <T,U>
WHAT:
- Implemented a generic class `Test2<T,U>` that supports two independent type parameters.
- Added fields `obj1` and `obj2` of types `T` and `U` respectively.
- Provided constructor for initialization and a `print()` method to display values.
- Created `GenericClassDemo2` with a demo instantiation: `Test2<String,Integer>`.
WHY:
- Demonstrates how Java Generics can handle multiple type parameters.
- Shows how to design reusable classes that store heterogeneous data while maintaining type safety.
- Example builds on the idea of single type parameter classes like `Box<T>`.
HOW:
- Declared `class Test2<T,U>` with two type parameters.
- `obj1` stores a value of type `T`, `obj2` stores a value of type `U`.
- Constructor initializes both values.
- `print()` outputs both stored objects.
- In `main()`, instantiated `Test2<String,Integer>` with `"Multiple parameter"` and `15`.
TYPE PARAMETER CONVENTIONS:
- `<T, U>` are placeholder names:
- `T` → Type (general placeholder)
- `U` → Second independent type
- Other common conventions:
- `E` → Element (used in collections like `List<E>`)
- `K` → Key
- `V` → Value
- `N` → Number
REAL-WORLD USE CASES:
- **Pairs/Tuples**: Represent related but different data types (e.g., name and ID).
- **Database records**: Store column name (`String`) with its value (`Object` or typed).
- **Key-value relationships**: Similar to `Map.Entry<K,V>` in Java Collections Framework.
- **Generic utility classes**: For passing/returning heterogeneous values safely.
NOTES:
- Unlike raw `Object`-based storage, generics eliminate the need for casting.
- Java’s `Map.Entry<K,V>` is a direct application of this pattern.
- Further enhancements could include methods like `getFirst()` and `getSecond()` for readability.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent e1e8b9e commit b900137
File tree
1 file changed
+8
-15
lines changed- Section24JavaGenerics/src/GenericClass2
1 file changed
+8
-15
lines changedLines changed: 8 additions & 15 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
1 | 2 | | |
2 | 3 | | |
3 | | - | |
4 | | - | |
5 | | - | |
6 | | - | |
| 4 | + | |
7 | 5 | | |
8 | 6 | | |
9 | | - | |
10 | | - | |
| 7 | + | |
11 | 8 | | |
12 | 9 | | |
13 | 10 | | |
14 | 11 | | |
15 | | - | |
16 | | - | |
| 12 | + | |
17 | 13 | | |
18 | 14 | | |
19 | 15 | | |
20 | 16 | | |
21 | 17 | | |
22 | | - | |
23 | | - | |
| 18 | + | |
24 | 19 | | |
25 | 20 | | |
26 | 21 | | |
27 | 22 | | |
28 | 23 | | |
29 | | - | |
30 | | - | |
31 | | - | |
32 | | - | |
| 24 | + | |
| 25 | + | |
33 | 26 | | |
34 | 27 | | |
35 | 28 | | |
36 | | - | |
| 29 | + | |
0 commit comments