Last week, we had the author of TDD for a Shopping Website LiveProject. Friday at 11am Ranch time, Steven Solomon will be hosting a live TDD session just for us. See for the agenda and registration link
In the case of casting.... It is done with primitives to cast one type of primitive into another type, and if you want to cast an object into another type , current object must be a sub type of the object which you are casting into.
int i= (int)24.34 and
String string1; Object obj1=(Object)string1; //Object is a super class of String, so we can cast ...
Wrappers are used to convert primitive data types into objects....
I was studying Type conversion and casting and wrapper classes. There are a few things I got messed up:
1. type conversion vs wrapper classes... basically whats the difference??? How will I know what to use??
2. I read a few examples abt casting one user defined class to a different one, if you have a really simple example on that, pls put that here, I would really appreciate it.
For your first question, you will frequently use both together.
You cannot store a primitive, such as an int or a boolean, in a Collection class like an ArrayList. So you need a wrapper class like Integer or Boolean to act as an container object.
Now you need to know that this discussion has completely neglected the autoboxing and unboxing features (new as of Java 1.5). These features should now make a whole lot more sense, as they have to do with automatically wrapping and uwrapping your primitives in this kind of scenario.
For your second question, suppose you have a user-defined Animal class, and you extend this to create Dog and Cat classes. And suppose you need to store these in an array of Animal objects. This works because a Cat or a Dog is an Animal object by virtue of inheriting from the Animal class.
If you extract your Animal objects from the array in a loop, you may not know if the object is a Dog or a Cat, only that it is an Animal. (You can confirm its actual type by use of the instanceof operator.)
If you want to call some "Cat-only" or "Dog-only" method, like Cat.cleanWhiskers() or Dog.chewSlippers(), then you are going to have to first cast your Animal to the Cat or Dog class, because the Animal class should have neither of those methods.
Make sense? [ February 09, 2007: Message edited by: Philip Shanks ]
Philip Shanks, SCJP - Castro Valley, CA
My boss never outsources or has lay-offs, and He's always hiring. I work for Jesus! Prepare your resume!
Clowns were never meant to be THAT big! We must destroy it with this tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss