ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

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

 

Facebook Comments

Check Your Domain Ranking

Leave a Reply

Your email address will not be published. Required fields are marked *

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!