Guest User

Untitled

a guest
Jun 13th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.55 KB | None | 0 0
  1. Object i = Integer.valueOf(42);
  2. String s = (String)i; // ClassCastException thrown here.
  3.  
  4. class A {...}
  5. class B extends A {...}
  6. class C extends A {...}
  7.  
  8. Animal a = new Dog();
  9. Dog d = (Dog) a; // no problem, the type animal can be casted to a dog, because its a dog
  10. Cat c = (Dog) a; // raises class cast exception, you cant cast a dog to a cat
  11.  
  12. public void manipulate(Object o) {
  13. Dog d = (Dog) o;
  14. }
  15.  
  16. Animal a = new Animal();
  17. manipulate(a);
  18.  
  19. Dog d;
  20. if(o instanceof Dog) {
  21. d = (Dog) o;
  22. } else {
  23. //what you need to do if not
  24. }
Add Comment
Please, Sign In to add comment