Commit f75702d
committed
feat: Demonstrate upcasting and downcasting with method overriding in Java
This commit introduces a Java program that clearly explains the concepts of:
- Upcasting (automatic)
- Downcasting (manual and type-checked)
- Method overriding
- `instanceof` check for safe casting
Key elements:
- Defined a base class `Animal` with a field `name` and a method `makenoise()`
- Created a subclass `Dog` that overrides `makenoise()` and adds a new method `growl()`
- In the `main` method:
- Upcasting: `Animal myAnimal = new Dog();` – a `Dog` object is referenced as its superclass type
- Demonstrated dynamic method dispatch: `myAnimal.makenoise()` calls the overridden method in `Dog`
- Explained unsafe downcasting: casting `new Animal()` to `Dog` results in `ClassCastException`
- Used `instanceof` to safely downcast only when the object is actually an instance of `Dog`
- Invoked the `growl()` method after safe downcasting
This example emphasizes best practices when working with polymorphism and casting in Java,
ensuring both flexibility (via upcasting) and safety (via `instanceof`) during object manipulation.
Signed-off-by: Somesh diwan <[email protected]>1 parent 4f9871e commit f75702d
1 file changed
+4
-3
lines changedLines changed: 4 additions & 3 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
19 | 19 | | |
20 | 20 | | |
21 | 21 | | |
| 22 | + | |
22 | 23 | | |
23 | 24 | | |
24 | 25 | | |
| |||
27 | 28 | | |
28 | 29 | | |
29 | 30 | | |
30 | | - | |
31 | | - | |
| 31 | + | |
32 | 32 | | |
| 33 | + | |
33 | 34 | | |
34 | 35 | | |
35 | 36 | | |
| |||
42 | 43 | | |
43 | 44 | | |
44 | 45 | | |
45 | | - | |
| 46 | + | |
0 commit comments