Table of Contents
Type Casting with Objects in Java
In Java, type casting with objects allows converting one object reference type into another. This is particularly useful when working with inheritance and polymorphism.
Types of Object Type Casting in Java
- Upcasting (Implicit Casting)
- Downcasting (Explicit Casting)
1. Upcasting (Implicit Casting)
Upcasting is the process of converting a subclass object into a superclass reference.
- This happens automatically (implicitly).
- Since the subclass "is a" type of the superclass, no explicit cast is needed.
class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void bark() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Animal a = new Dog(); // Upcasting (Implicit) a.sound(); // Allowed (inherited method) // a.bark(); // Not allowed (specific to Dog) } }
✅ Key Points:
- The
Dogobject is assigned to anAnimalreference. - The
sound()method can be called because it exists inAnimal. - The
bark()method cannot be accessed becauseAnimaldoes not have it.
2. Downcasting (Explicit Casting)
Downcasting is the process of converting a superclass reference back into a subclass reference.
- This requires explicit casting because not all superclass objects are actually instances of the subclass.
- A
ClassCastExceptionoccurs if the object is not of the expected type.
Example of Downcasting
class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void bark() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Animal a = new Dog(); // Upcasting Dog d = (Dog) a; // Downcasting (Explicit) d.bark(); // Now allowed } }
✅ Key Points:
- The object must actually be an instance of the subclass before downcasting.
- If the object is not of the correct type, Java throws a
ClassCastException.
Using instanceof to Avoid ClassCastException
To avoid ClassCastException, always check an object’s type using instanceof before downcasting.
if (a instanceof Dog) { Dog d = (Dog) a; // Safe Downcasting d.bark(); } else { System.out.println("Downcasting not possible"); }
Summary Table
| Type | Definition | Example |
|---|---|---|
| Upcasting | Converting subclass to superclass | Animal a = new Dog(); |
| Downcasting | Converting superclass to subclass (requires explicit casting) | Dog d = (Dog) a; |
| Safe Downcasting | Use instanceof to check before downcasting |
if(a instanceof Dog) { Dog d = (Dog) a; } |
Key Takeaways
✅ Upcasting is automatic and safe.
✅ Downcasting requires explicit casting and should be checked using instanceof to avoid exceptions.
✅ Always ensure that an object is actually an instance of the subclass before performing downcasting.
If you require additional resources, consider purchasing: ICSE Computer Applications Class 10 – Previous Year Question Papers & Solutions (Java Fundamentals)