Larry Chung wrote:Yes, good point. I had thought runtime type would trump compile time type. Or does that come into play at all?
No, the runtime type is not considered - the compiler only looks at the compile-time type (it can't know the runtime type at compile-time). In general, the runtime type is not used for these kind of checks, because it means that extra code would have to run that does those checks at runtime, which would make the program run slower.
One exception where
Java does add a runtime check is with arrays. You could for example write the following:
This compiles, because the static type of
data is array of
Object. The runtime type, however is array of
String, so
you should not be able to store an
Integer in this array. If you run this, you get:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
at org.jesperdj.sandbox.JavaRanch.main(JavaRanch.java:6)
Java does a check at runtime (the array store check) every time you store an object in an array. Some people have criticized this, because it makes arrays in Java less efficient than in for example C or C++, where no such runtime check is done.