Author | Topic: Reference conversion |
Linda Xu greenhorn |
posted March 07, 2000 12:12 PM
In Bill Brogden's Exam Cram book, page 110. When talking about " a class reference can be converted to:", it said" any class reference with runtime check", what does it mean? Does it mean I can use explicit cast to cast a class reference to any class reference without complaint in compile? But I tried the following code: So, Does that mean I can cast to some "Valid" class reference? What classes are valid? How to understand Bill's statement in book? Thank you very much!
|
maha anna bartender |
posted March 07, 2000 12:31 PM
You can cast a class to another class provided these 2 classes are in the same branch of the class hierarchy and either of these 2 classes MUST be superclass of the other. Otherwise the compiles easily finds the classes are totally unrelated and throws "Invalid cast error".
regds maha anna
|
Jim Yingst sheriff |
posted March 07, 2000 12:46 PM
[I see maha anna was too fast for me - still, I'll leave this up as it has some additional info. - Jim] I think Bill's statement is not entirely correct, as you've discovered. (But I don't have the book, so maybe there's more to the statement?) If you cast a reference to the same type as the reference type, or a superclass or superinterface, then the compiler will say OK, and won't even bother to check at run-time (the cast is guaranteed to be correct, and it's unnecessary). If you cast a reference to a subclass of the reference type, or to any interface not already implemented by the reference type, then the compiler will say OK for now, but will tell the JVM to check at run-time, because the reference could refer to a subclass instance, which may also have implemented other interfaces. If you cast a reference to an unrelated class (not interface), then the compiler knows there is no way the reference can ever hold an object of that type, and so the compiler will complain at compile time. So, for a variable declared as "
[This message has been edited by Jim Yingst (edited March 07, 2000).]
|
William Brogden unregistered |
posted March 07, 2000 02:51 PM
quote: Look at the top of the page. It says these are the conversions that can be legally coded. - In other words, the compiler will not throw them out. To pass the runtime check the actual reference will have to be of the proper type.
|
William Brogden unregistered |
posted March 07, 2000 03:14 PM
quote: Whoops, that first reply was off the mark, now that I re-read the question, let me try again. The cast it is talking about is a class reference, not a reference to an instance of a class. As in something like this: Class c = Class.forName( java.awt.Frame );
|
Jim Yingst sheriff |
posted March 07, 2000 03:36 PM
Aha! Cool, my faith in humanity (or William Brogden at least) has been restored. Thanks William!
|
| | |