• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reference Variable Casting

 
ragi singh
Ranch Hand
Posts: 198
Oracle Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi I have the following piece of code


When i run the code i get the following exception :- Class cast exception at line Line 1 . My question is , Java allows downcasting then why is my code failing to compile ?
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ragi singh wrote:
My question is , Java allows downcasting then why is my code failing to compile ?

You have misunderstood the down casting. Clue: Down casting for reference variable, not to objects. If you allowed to cast object, then what will be the real logic? You can't cast a object to any other object!
 
Minhaj Mehmood
Ranch Hand
Posts: 400
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Think about the relationships in real life, such as: A child can become parent, but a parent cannot become child again

Test2 is parent and you're forcing it to become child.


Hope this helps

Minhaj
 
ragi singh
Ranch Hand
Posts: 198
Oracle Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that is to say we cannot downcast objects ?
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ragi singh wrote:that is to say we cannot downcast objects ?


You can't cast a object! You can make sub class objects with super class reference and make a down cast it to refer with sub class reference again.
 
ragi singh
Ranch Hand
Posts: 198
Oracle Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok i got it now thank you .
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are Welcome. If we are allowed to cast a object into another, then there is no point of talking polymorphism and other stuff in Java! I think, now you got what does mean by down casting and up casting!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic