+ 1

Downcasting help

can someone check what is wrong with my downcasting code https://code.sololearn.com/cWnu3boE0x0T/?ref=app

26th Oct 2017, 8:51 AM
oyl
8 Answers
+ 2
you cant downcast it cuz p1 actual type is pokeman,not pickachu inorder to downcast it you should do Pokeman p1=new Pickachu (); ((Pickachu)p1).sound ();
26th Oct 2017, 8:59 AM
Haileyesus Shitalem
Haileyesus Shitalem - avatar
+ 9
Now it prints Pika pika :) Since all Pokemons cannot be treated as Pikachu, it throws ClassCastException. https://code.sololearn.com/cRs9242ze4wP/#java
26th Oct 2017, 9:04 AM
Shamima Yasmin
Shamima Yasmin - avatar
+ 8
@oyl, this discussion will help you. They have discussed exact same concept. See the best answer here : https://stackoverflow.com/questions/23414090/what-is-the-difference-between-up-casting-and-down-casting-with-respect-to-class
27th Oct 2017, 4:28 AM
Shamima Yasmin
Shamima Yasmin - avatar
+ 7
In simple terms, The first statement is equivalent to "Pokemon p1 is a Pokemon". Now p1 can access all properties of Pokemon but it can't access the properties of Pikachu. The second statement is equivalent to "Pikachu p1 is a Pokemon". Now since the type is Pokemon and TYPE GETS PRIORITY, it can access all properties of Pokemon normally. To access properties of Pikachu, we need to downcast it to Pikachu. Note: All Pikachus are Pokemon, but all Pokemons are not Pikachu. So the following statement will be invalid. Pikachu p1 = new Pokemon(); //wrong
26th Oct 2017, 1:19 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 1
@ Shamima Yasmin @Haileyesus Shitalem what is the difference betweem Pokemon p1=new Pokemon(); and Pokemon p1=new Pikachu();?
26th Oct 2017, 10:26 AM
oyl
0
@Shamima Yasmin sorry i still dont get it
26th Oct 2017, 11:56 PM
oyl
0
when u write Pokemon p1=new Pokemon (); u r bascally saying the data type of p1 is pokeman and the actual data is also pokeman but when u write Pokeman p1=new Pikachu (); what it means is the data type is pokeman but the actual data is pikachu,this is possible since pikachu is a pokeman
27th Oct 2017, 6:57 PM
Haileyesus Shitalem
Haileyesus Shitalem - avatar
0
...continued ) Eg Shape shape=new Shape (); Shape shape=new Circle (); you cant cast the first one to circle since a shape is not a circle it can be square...but u can cast the second to shape since a circle is a shape.clear???
27th Oct 2017, 7:02 PM
Haileyesus Shitalem
Haileyesus Shitalem - avatar