+ 1
Downcasting help
can someone check what is wrong with my downcasting code https://code.sololearn.com/cWnu3boE0x0T/?ref=app
8 ответов
+ 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 ();
+ 9
Now it prints Pika pika :) Since all Pokemons cannot be treated as Pikachu, it throws ClassCastException.
https://code.sololearn.com/cRs9242ze4wP/#java
+ 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
+ 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
+ 1
@ Shamima Yasmin @Haileyesus Shitalem
what is the difference betweem
Pokemon p1=new Pokemon();
and
Pokemon p1=new Pikachu();?
0
@Shamima Yasmin sorry i still dont get it
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
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???