📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
ClassCastException has thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
This exception extends the RuntimeException class and thus, belongs to those exceptions that can be thrown during the operation of the Java Virtual Machine (JVM). It is an unchecked exception and thus, it does not need to be declared in a method’s or a constructor’s throws clause.
ClassCastException Class Diagram
Common Scenarios
Java ClassCastException Example #1
public class ClassCastExceptionExample {
public static void main(String[] args) {
Object obj = new Integer(100);
System.out.println((String) obj);
}
}
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at ClassCastExceptionExample.main(ClassCastExceptionExample.java:4)
Java ClassCastException Example #2
package com.javaguides.corejava;
class Animal {
}
class Dog extends Animal {
}
class Lion extends Animal {
}
public class ClassCast {
public static void main(String[] args) {
try {
Animal animalOne = new Dog(); // At runtime the instance is dog
Dog bruno = (Dog) animalOne; // Downcasting
Animal animalTwo = new Lion(); // At runtime the instance is animal
Dog tommy = (Dog) animalTwo; // Downcasting
} catch (ClassCastException e) {
System.err.println("ClassCastException caught!");
e.printStackTrace();
}
}
}
ClassCastException caught!
java.lang.ClassCastException: com.javaguides.corejava.Lion cannot be cast to com.javaguides.corejava.Dog
at com.javaguides.corejava.ClassCast.main(ClassCast.java:24)
Handling ClassCastException
Best Practices
- Keep inheritance hierarchies clear and straightforward, reducing the chances of inadvertent typecasting.
- Favor composition over inheritance when designing classes. This approach reduces the overall need for casting and the associated risks.
- Whenever you feel the urge to use explicit casting, double-check your design decisions. There's often a better way.
Comments
Post a Comment
Leave Comment