• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Casting issue  RSS feed

 
Bhaskar Jakkaraddi
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
3. public class Redwood extends Tree {
4. public static void main(String[] args) {
5. new Redwood().go();
6. }
7. void go() {
8. go2(new Tree(), new Redwood());
9. go2((Redwood) new Tree(), new Redwood());
10. }
11. void go2(Tree t1, Redwood r1) {
12. Redwood r2 = (Redwood)t1;
13. Tree t2 = (Tree)r1;
14. }
15. }
16. class Tree { }

Would some one explain easy way to figure out casting run time error in the above type of code?
 
Stephan van Hulst
Saloon Keeper
Posts: 7972
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because at line 9 you're making a new Tree, and casting it to a Redwood. Redwoods may be Trees, but Trees are not Redwoods.
 
Campbell Ritchie
Marshal
Posts: 56533
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use the code button and indent your code correctly; your posting is difficult to read otherwise.
 
Mohamed Sanaulla
Bartender
Posts: 3185
34
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In real implementations- Its always better to use instance of before casting, so that you can avoid the class cast exception.

In your first go2() call at line 8- You are creating an Instance of Tree. And then in the go2() method you are trying to cast it to Redwood which Is not possible.

You can try passing in an Instance of Redwood as the first argument to go2() in which case it doesnt throw the exception. At run time JVM checks what object actually it is- a Tree or a Redwood and checks if it can do the cast. If its a Tree object it throws an Exception as already mentioned by Stephan.
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And it would be nice to quote the source.
 
Campbell Ritchie
Marshal
Posts: 56533
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mohammed sanaullah wrote:In real implementations- Its always better to use instance of before casting, . . .
Wouldn't it be better to design your application to avoid casting at all?
 
Mohamed Sanaulla
Bartender
Posts: 3185
34
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Wouldn't it be better to design your application to avoid casting at all?


Agree. Casting at times will lead to problems.
 
Campbell Ritchie
Marshal
Posts: 56533
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mohammed sanaullah wrote: . . . Agree. . . .
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!