Hi Kruger, I am not sure what it really is, but that is what book "Thinking in Java says:"
In C++, the classic cast “(Shape)” does not perform RTTI. It simply tells the compiler to treat the object as the new type. In Java, which does perform the type check, this cast is often called a “type safe downcast.” The reason for the term “downcast” is the historical arrangement of the class hierarchy diagram. If casting a Circle to a Shape is an upcast, then casting a Shape to a Circle is a downcast. However, you know a Circle is also a Shape, and the compiler freely allows an upcast assignment, but you don’t know that a Shape is necessarily a Circle, so the compiler doesn’t allow you to perform a downcast assignment without using an explicit cast.
and that is what java.sun.com says:
Type safety. Java objects are always type safe, preventing bugs that would occur if a programmer makes a mistake about the type of an object.
So, I suppose that casting one type to another one which are not compatible throws ClassCastException preventing from implementation bugs. I hope it helps. If it is a wrong answer, please anyone correct me. Regards, Vlad [ September 09, 2003: Message edited by: Vlad Rabkin ]
Hi Kruger, I understand Vlad wondering why you ask that question after having passed your SCJD exam with ... 94.25%. No sarcasm at all from me, but it's seems weird to me too. As I understand it myself, Java is said "type safe" because both its compiler and the JVM check whether both operands of any assignment are type-compatible. The compiler accepts any is-a-A-Class B object to be assigned to some A-Class variable :
The JVM will check at run time the validity of your explicit typecasts :
In comparison, C++ is not type-safe : you are free to typecast a pointer from one type to any other type without any complaint neither at compile time nor at run time (except a possible memory access violation or just weird results in you do it wrong). It's your responsability to know and understand what you do, but it can be handy though. Best, Phil. PS: Sorry Vlad, my answer crossed yours... [ September 09, 2003: Message edited by: Philippe Maquet ]
Hi Kruger, Vlad's explanation is nearly all there. The minor missing part is that Java checks types at compile time. So at runtime you know that all the assignments to types are safe, unless you as the programmer have explicitly overriden the normal type safety by using a cast. I don't believe this discussion really belongs in SCJD thought. I have moved it to Java In General (Beginner) where it can keep this thread and this thread company. I know you are no beginner, but this is the sort of question that beginners may be interested in. Regards, Andrew