• Post Reply Bookmark Topic Watch Topic
  • New Topic

Object Casting Not Functioning Properly  RSS feed

 
Chris Avila
Greenhorn
Posts: 16
Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does my following method not cast properly? As far as I see, this should not create any casting issues.

       

I know that the following would work, however I feel uncomfortable that the top example does not.

      

Any pointers as to why the first example does not work would be very much appreciated my fellow developers I am casting string1 to a String, and it seems it is not casted?
 
Ivan Pronin
Greenhorn
Posts: 21
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you should create new object references for casting to work. In your example string1 and string2 variables still point to the same Object types as before casting:
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chris Avila wrote:Why does my following method not cast properly? As far as I see, this should not create any casting issues.
       

You might have seen the problem sooner had you not chosen names that reflected your knowledge of what the objects were that you were passing in to this method. Casting an Object to String will only work as long as the only kind of objects you pass to this method are String objects. Since the method declares its parameters as Object, there's really no guarantee that this method will always receive Strings. What happens when someone who doesn't know that this method is  supposed to be passed only String objects passes it some other type of object, thinking that it should be ok, since the method signature says it will take any Object reference? It will throw a ClassCastException! This is bad code and  it would have been more evident how bad it was if you had used different names instead:

The only thing I changed here are the names. It was misleading to use "stringX" with references that were really of type Object. Now it's clearer that you're trying to cast an Object to a String but then you're assigning that reference right back to an Object. Since an Object has no length() method, you should expect to get a compiler error on those lines that are marked with "// Issue".
 
Chris Avila
Greenhorn
Posts: 16
Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys! Appreciate the help.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!