How to avoid class cast Exception in Java

0
6

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:

  1. //Here A, B, C and D are four classes
  2.  
  3. class Manager{
  4. public static void main (String[] args){
  5. A a1 =new C ();
  6. B b1=(B) a1;
  7. C c1=(C) b1;
  8. if (a1 instanceOf A){
  9. A a2=(A)a1;
  10. System.out.println("A");
  11. }
  12. if (a1 instanceOf B){
  13. B b1=(B)a1;
  14. System.out.println("B");
  15. }
  16. if (a1 instanceOf C){
  17. C c1=(C)a1;
  18. System.out.println("C")
  19. }
  20. if (a1 instanceOf D){
  21. D d1=(D)a1;
  22. System.out.println("D")
  23. }
  24. }
  25. }
  26.  
  27. Output:
  28.  
  29. A
  30.  
  31. B
  32.  
  33. C

 

Readers might read this also:

 

 

Facebook Comments
(Visited 3 times, 1 visits today)

LEAVE A REPLY

Please enter your comment!
Please enter your name here