Showing posts with label Incompatible types. Show all posts
Showing posts with label Incompatible types. Show all posts

Thursday, 29 March 2012

ClassCastException in Java

public class ClassCastException
extends RuntimeException

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. i.e.Thrown when attempting to cast a reference variable to a type that fails the IS-A test.

Before discussing more about ClassCastException let us go through reference variable casting.

Reference Variable Casting

Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.The compatible data types means they should follow the following contracts.

1. Both the reference variables types should be in the same inheritance hierarchy.Else compile-time error occurs.
2. When attempting to cast a reference variable to a type that should pass the IS-A test.Else run-time error occurs ,i.e. throws ClassCastException.