All About Class ClassCastException in Java



Casting refers to the terminology where an instance of a class of one type can be made to cast to for another type.But there is a rule to it. An instance of a class can be casted to its super class but one can not cast an instance of a class to its subclasses.

ClassCastException is thrown from a program to indicate that the code has attempted to cast an object to a subclass of which it is not an instance or it could be due to incorrect type.
However it is possible to avoid this exception by checking the type first using instanceOf operator or method.
The structure of the class is as follows:


public class java.lang.ClassCastException extends java.lang.RuntimeException{
//constructor
public ClassCastException();
//constructs an empty ClassCastException object that is an object with no message specified.
public ClassCastException(String message);
//constructs an ClassCastException object with the message specified.
}
 

Let us check some example: In this example assume that Class ClassA has two child classes ClassB and ClassC.
      ClassA
         / \
ClassB ClassC


class ClassA{
}
class ClassB extends ClassA{
void MethodB()
{
....
}
}
class ClassC extends ClassA{
void MethodC()
{
....
}
}
class Test{
void castTest()
{
//possible
ClassA a new ClassA();
ClassB b=(ClassB)new ClassA();
ClassA b=new ClassB();
ClassA a1=new ClassC();
//not possible
ClassB b1=new ClassC();
ClassB b2=new new ClassA();
ClassC c1=new ClassB();
}
}
 
All About Class ClassCastException in Java All About Class ClassCastException in Java Reviewed by Animesh Chatterjee on September 17, 2018 Rating: 5

No comments:

Powered by Blogger.