Commit c388241
committed
feat: Implement example demonstrating upcasting and downcasting in Java with method overriding
This commit adds a Java program that illustrates key object-oriented programming concepts:
- Upcasting (child to parent reference)
- Downcasting (parent reference back to child)
- Method overriding and dynamic method dispatch
Key changes:
- Defined a `Parent` class with a `name` attribute and a `method()` printing a message
- Defined a `Child` class that extends `Parent`, adds an `id` attribute, and overrides the `method()`
- In the `main()` method:
- Performed **upcasting**: `Parent p = new Child();` and demonstrated access to inherited fields and overridden methods
- Showed **method dispatch behavior**: `p.method()` executes the overridden method in `Child`
- Performed **explicit downcasting** safely: `(Child)p` to access subclass-specific field `id`
- Printed both inherited and child-specific data to verify proper object behavior after downcasting
This example reinforces Java's runtime polymorphism and the correct approach to accessing subclass features after safe downcasting.
Signed-off-by: Somesh diwan <[email protected]>1 parent f75702d commit c388241
1 file changed
+12
-7
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
4 | | - | |
| 3 | + | |
| 4 | + | |
5 | 5 | | |
6 | 6 | | |
7 | 7 | | |
| 8 | + | |
8 | 9 | | |
9 | 10 | | |
10 | | - | |
11 | | - | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
12 | 14 | | |
13 | 15 | | |
14 | 16 | | |
| 17 | + | |
15 | 18 | | |
16 | | - | |
17 | | - | |
| 19 | + | |
| 20 | + | |
18 | 21 | | |
19 | 22 | | |
20 | 23 | | |
21 | 24 | | |
| 25 | + | |
22 | 26 | | |
23 | 27 | | |
24 | 28 | | |
25 | 29 | | |
26 | 30 | | |
27 | 31 | | |
| 32 | + | |
28 | 33 | | |
29 | 34 | | |
30 | 35 | | |
31 | 36 | | |
32 | | - | |
| 37 | + | |
0 commit comments