Upcasting and Downcasting
Type conversion in inheritance
5 min read
Upcasting & Downcasting
Upcasting is safe and implicit. Downcasting is explicit and requires instanceof check.
Code Examples
Safe and unsafe type casting
java
1
2Animal a = new Dog(); // Upcasting
3
4if (a instanceof Dog) {
5 Dog d = (Dog) a; // Downcasting
6 d.bark();
7}
8 Use Cases
- Generic processing
- Framework internals
- Runtime object handling
Common Mistakes to Avoid
- Casting without instanceof
- Assuming all parents are children