• Post Reply Bookmark Topic Watch Topic
  • New Topic

Casting  RSS feed

 
jose chiramal
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have two lines of code as shown below :

public class Test1 implements Interface1


Interface1 int1 = (Interface1) new Test1();

Can we call this as downcasting ? Or is casting exclusive only for classes ?The rule in downcasting is that we must explicilty write the cast and the object must be a legitimate instance of the class we are casting to. This doesnt seem to have been followed in my code above.
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did you try it out? Does it compile? Does it compile without the explicit cast?
 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jose : Casting up (toward Object) is good and very
useful, while casting down can be quite dangerous.
Jim ... ...
 
jose chiramal
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Maneesh Godbole,

I tried this without the explicit cast and it works.

public class Test1 implements Interface1
Interface1 int1 = new Test1();


Is this downcasting in any way ??? I do not think its downcasting since the statement "You can cast down the hierarchy as well but you must explicitly write the cast and the object must be a legitimate instance of the class you are casting to."

If not downcasting then what is it. Its not upcasting either, correct ??
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This recent thread may help.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!