Make visible what, without you, might perhaps never have been seen. - Robert Bresson
Joined: Sep 25, 2005
i donot have any particular example.. but shouldn't there be some sort of a generic rule for this which will work for all examples ???
Joined: Dec 06, 2001
Sure there are specific rules. If you want the nitty-gritty details you can read the Java Language Specification. In a nut shell, you must use a cast when you are assigning a variable of a general type to a more specific type. For example, if you want to assign a long value to an int or a int to a byte, you must use a cast because the first has a larger range (i.e. is more general) than the later. Another example is if you have a base class reference, then you must perform a cast to assign it to a child class. I think a code example will illustrate this more clearly than the above description:
What do you mean by "casting is required"? A well-designed application with no third party dependancies on "not-so-well-designed" applications/API will implicitly have no casts. That is to say, the use of casting is to workaround the existance of dependancy flaws, and never anything else, even if inadvertant.
Do you mean, what cases are required by the compiler?
>> Can anyone tell me when type casting is a must?
The compiler will tell you so you can relax. The most important fact to remember is that a reference can refer to objects of the same type or to objects that are extensions of the reference type:
Pet pet; pet = new Cat(); pet = new Dog();
An Object reference can refer to anything, by definition:
Object object; object = new Cat(); object = new Dog(); object = new Apple(); object = new Lexus();
Now her'e the rub. Let's say you want to cruise in your Lexus:
object.cruise(); // OOPS!
The Object has no such method as cruise. You know you stuffed a Lexus in that reference, so how do you call the Lexus methods?
((Lexus)object).cruise(); // Sweet!
Next question you should be asking is why not declare references that are of the correct type? The answer is primarily the use of old-style Java collections that return an Object type when fetching something out of the collection.