1 2 Previous Next 24 Replies Latest reply: Aug 28, 2008 10:23 AM by 843785 RSS

    Object Casting

    843785
      Would someone please explain how Object Casting works. I read about the concept in a java programming book but didn't fully understand it.
        • 1. Re: Object Casting
          843785
          You cast references, not objects. Important difference. Here's how it works
          Object object = "this is an object";
          // how long is the string?
          int len = object.length(); // compiler error - Object doesn't have that method
          Can't do that. Even though the object is a string, it's referred to as an Object. I need to treat it like a String, so I cast it:
          Object object = "this is an object";
          String string = (String) object;
          int len = string.length();
          See? The object is, and always will be, an instance of java.lang.String. Casting it doesn't change that

          Now, it isn't magic. You can't just cast anything to anything else and hope it works. The type you cast to has to be a type that the object actually has. The following won't work
          Object object = "this is a string";
          Socket s = (Socket) object; // won't work
          • 2. Re: Object Casting
            843785
            georgemc wrote:
            You cast references, not objects. Important difference.
            It's an extremely important difference, which makes it somewhat of a shame that [The Java? Tutorial|http://java.sun.com/docs/books/tutorial/java/IandI/subclasses.html] has a whole section on "Casting Objects". Urgh. Perhaps the authors felt that at an introductory conceptual level, references can be thought of as the objects themselves. But it's been my experience on this forum that such conflation results in a great deal of confusion.

            Of course, that fails to account for all the people who read the tutorial and aren't confused about how casting actually works. I don't get to see those posts. :o)

            ~
            • 3. Re: Object Casting
              843785
              yawmark wrote:
              georgemc wrote:
              You cast references, not objects. Important difference.
              It's an extremely important difference, which makes it somewhat of a shame that [The Java™ Tutorial|http://java.sun.com/docs/books/tutorial/java/IandI/subclasses.html] has a whole section on "Casting Objects".
              It does? Yikes! I was wondering where the OP had seen the phrase. That's awful, we should petition Sun to change it. Seriously
              • 4. Re: Object Casting
                843785
                I'm confused!

                If Man extends Human:
                Man m = new Man();
                ((Human)m).getHeight(); // i.e.
                is that not casting an object?

                regards
                • 5. Re: Object Casting
                  843785
                  phdk wrote:
                  I'm confused!

                  If Man extends Human:
                  Man m = new Man();
                  ((Human)m).getHeight(); // i.e.
                  is that not casting an object?
                  It is, but it's a pointless cast. What's confusing?
                  • 6. Re: Object Casting
                    843785
                    Well okay! I see the pointless cast i my example.
                    But from the tutorial :
                    if (obj instanceof MountainBike) {
                       MountainBike myBike = (MountainBike)obj;
                    }
                    Is that casting a ref? is it pointless? I believe the tutorial is about casting class instances and not references!

                    rgds

                    Peter
                    • 7. Re: Object Casting
                      843785
                      Yes, casting works on references, not objects. The comment about being useless was (most likely) referring to upcasting, which is useless.
                      • 8. Re: Object Casting
                        843785
                        phdk wrote:
                        Well okay! I see the pointless cast i my example.
                        But from the tutorial :
                        if (obj instanceof MountainBike) {
                        MountainBike myBike = (MountainBike)obj;
                        }
                        Is that casting a ref? is it pointless? I believe the tutorial is about casting class instances and not references!
                        See above: the tutorial is poorly worded. It is in fact about casting references
                        • 9. Re: Object Casting
                          843785
                          Thanks!
                          • 10. Re: Object Casting
                            800308
                            You can't magically change the type of an object... If you instantiate a MountainBike it's allways going to be a MountainBike... you can't then decide your nice new red mountainBike is in fact a pink girlsBike... it just isn't... what casting allows you to do is narrow a reference to a mountainBike which (for example) came as part of a collection of Bike's back to it's actual type, which is MountainBike
                              List<Bike> bikes = new ArrayList<Bike>();
                              bikes.add(new MountainBike("red"));
                              ... sometime later ...
                              Bike bike = bikes.get(0);
                              if (bike instanceof MountainBike) {
                                MountainBike mountainBike = (MountainBike) bikes.get(0);
                                mountainBike.changeGear(-3); // steep ascent.
                              }
                            ... Note that relying on instanceof all over the place is evidence of poor design... you can write your code in such a way that the above yucky "sometime later" code doesn't need to know exactly what type of bike it is dealing with... if all bikes can be shanghaid into presenting a consistent interface then you can use them via that interface, and let the magic of dynamic binding chose the "best available" implementation of that behavior... ergo:
                            interface Bicycle {
                              double startAscent(double gradient);
                              ... other methods ...
                            }
                            
                            class MountainBike implements Bicycle {
                               ... attributes, contructors and stuff ...
                               double startAscent(double gradient) {
                                 this.changeGear(gradient-90 / numgears);
                                 return this.getCurrentGearRatio();
                               }
                            }
                            
                            class GirlsBike implements Bicycle {
                               ... attributes, contructors and stuff ...
                               double startAscent(double gradient) {
                                 this.fixMakeUp();
                                 if (gradient > 1D/12D) {
                                   this.setHint("Get off and push ya big skirt!");
                                 }
                                 return 1.0;
                               }
                            }
                            Hope that helps (more than it confuses)...

                            Cheers. Keith.

                            Edited by: corlettk on 29/08/2008 00:21 - Ooops!
                            • 11. Re: Object Casting
                              843785
                              Object object = "this is an object";
                              // how long is the string?
                              int len = object.length(); // compiler error - Object doesn't have that method
                              Ok Are you essentially saying that you can't cast object.length() call because object isn't of type String so it therefore doesn't have access to string methods?


                              Please help me understand the value of downcasting a reference (from say Parent Class Fruit to subclass Apple or Orange)? What real value do you get from this?
                              By doing this does the Fruit reference now have say Apple methods?

                              Also help me understand the value of upcasting a reference (from Sublcasses Orange or Apple to Parent class Fruit)? What real value do you get from this?
                              By doing this does the Apple reference now lose all its methods and only contain Fruit methods? I don't see the value in this.
                              • 12. Re: Object Casting
                                843785
                                villumanati wrote:
                                Object object = "this is an object";
                                // how long is the string?
                                int len = object.length(); // compiler error - Object doesn't have that method
                                Ok Are you essentially saying that you can't cast object.length() call because object isn't of type String so it therefore doesn't have access to string methods?
                                Kind-of. Object doesn't have a method called length, but String does. The really really important thing to remember is, if the object you're dealing with isn't of the type you're trying to cast to, the cast won't work. A lot of people, when new to casting, think that it's some magical operation that allows them to change the type of any object to any other. So you'll see posts about "I can't cast my TextField to String" and the like. Doesn't work like that

                                >
                                Please help me understand the value of downcasting a reference (from say Parent Class Fruit to subclass Apple or Orange)? What real value do you get from this?
                                By doing this does the Fruit reference now have say Apple methods?
                                Not quite, but you're getting the idea. You now have an Apple reference, thus, access to Apple methods.
                                Also help me understand the value of upcasting a reference (from Sublcasses Orange or Apple to Parent class Fruit)? What real value do you get from this?
                                By doing this does the Apple reference now lose all its methods and only contain Fruit methods?
                                Again, you will have a reference to a Fruit, not an Apple.
                                I don't see the value in this.
                                There generally isn't any value in that, no. Implicit upcasts might happen if you pass a subtype reference into a method which takes a supertype as an argument:
                                void eat() {
                                   Apple apple = new Apple();
                                   peel(apple);
                                }
                                
                                void peel(Fruit fruit) {
                                   // you get Fruit. Doesn't matter what type of fruit it is, you'll only have access to Fruit methods
                                 }
                                • 13. Re: Object Casting
                                  843785
                                  Ok thanks everyone for your help Reference Castings makes a lot more sense now.

                                  One last question Would someone explain what is going on in lines 3 and 4 below with respect to references and objects that each of the lines point to?


                                  public class Employee{}
                                  
                                  public class VicePresident extends Employee {}
                                  -----------------------------------
                                  
                                  1. Employee emp = new Employee();
                                  2. VicePresident veep = new VicePresident();
                                  3.  veep = emp;
                                  4.  veep = VicePresident (emp);
                                  • 14. Re: Object Casting
                                    843785
                                    villumanati wrote:
                                    One last question Would someone explain what is going on in lines 3 and 4 below with respect to references and objects that each of the lines point to?
                                    Those lines won't compile. The error messages will tell you why.

                                    ~
                                    1 2 Previous Next