This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Richard When you do this type of thing in your code it is always helpful to keep in mind the 'is a' and 'has a' phrases. In your first example lets use the 'is a' phrase and look at it line by line. // create an Integer Integer i1 = new Integer("1"); /* assign a variable 'o' to refer to the new Integer object. Even though o is supposed to refer to an Object object you can have it refer to an Integer Object because an Integer is a Object. */ Object o = i1; /* create a new Integer varaiable i2 and have it refer to the object that o refered to but cast to an Integer. The variable o refers to an object of type Object so without the cast you would get a reference to an Object. The cast works because in the previous line we made o refer to an Integer object, so we can cast back to that same object. */ Integer i2 = (Integer) o; // print the object refered to by i1 System.out.println(i2); Now lets look at the second example you posted: // create a new java.util.Date object java.util.Date ud = new java.util.Date(); /* The compiler will let you cast this and it will accept it because the actual types will not be checked until runtime. At runtime however, it will fail because you are trying to cast a java.util.Date into a java.sql.Date object and a util.Date is not a sql.Date. */ java.sql.Date sd = (java.sql.Date) ud; Hope that helped [ April 11, 2002: Message edited by: Dave Vick ]
You need to rember one thing about casting. It only changes the reference type to the Object not the Object. You can cast up until you reach the Object itself and then no further. The example you gave has a tree of Object - java.util.Date - java.sql.Date So, you can do a Object o = new java.util.Date() java.util.Date d = (java.util.Date)o; Going up the tree but not passing the actual object. But, Object o = new java.util.Date(); java.sql.Date d = (java.sql.Date)o; is illegal because it goes further up the tree than the actual Object. [ April 11, 2002: Message edited by: Carl Trusiak ]