Type Casting in Practice
Apply type casting in real-world scenarios including numeric calculations and OOP hierarchies.
Type Casting in Practice
Type casting is used everywhere in real Java code: numeric calculations, OOP hierarchies, generic collections, and legacy APIs. This lesson covers practical patterns and pitfalls.
Upcast: Polymorphism
An upcast converts a subtype to a supertype. It is always safe and implicit — no cast operator needed. This enables polymorphism.
class Payment {}
class CreditCardPayment extends Payment {
public void authorizeCard() {}
}
CreditCardPayment cc = new CreditCardPayment();
Payment p = cc; // implicit upcast — always safe
// p.authorizeCard(); // Compile error — Payment doesn't have this method
// need downcast to access subclass methodsAll lessons in this course
- Primitive vs Reference Types
- Widening and Narrowing Conversions
- The instanceof Operator
- Type Casting in Practice