How to avoid class cast Exception in Java

0
87

This tutorial is all about How to avoid class cast Exception in Java.
Many time we might see class cast exception while execution of our code. In order to avoid this exception we need to use instance of operator in our code.

Let us take one example:

[java]

//Here A, B, C and D are four classes

class Manager{
public static void main (String[] args){
A a1 =new C ();
B b1=(B) a1;
C c1=(C) b1;
if (a1 instanceOf A){
A a2=(A)a1;
System.out.println(“A”);
}
if (a1 instanceOf B){
B b1=(B)a1;
System.out.println(“B”);
}
if (a1 instanceOf C){
C c1=(C)a1;
System.out.println(“C”)
}
if (a1 instanceOf D){
D d1=(D)a1;
System.out.println(“D”)
}
}
}

Output:

A

B

C

[/java]

 

Readers might read this also:

 

 

Facebook Comments

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.