If there is a suitable or matching typecasting present, the compiler is happy with it.
If you could try the same program after removing the typecasting, it will definitely throw an error.
Eventhough it compiles fine, at the runtime you will definitely get an error because of incompatible object of class which does NOT implement the interface.
Look at the modified program below
Run as it is. Though it compiles fine because of the proper typecast, it will throw a "ClassCastException" at runtime.
Comment line 1 and Uncomment line 2. and then compile run. Here the compiler itself will throw an error because of no proper typecasting.
Comment line 1 and 2 and Uncomment line 3. Now compile and run. It will NOT only pass the compilation but also the execution. Because at runtime also the object being passed passes the "IS-A Bicycle" test. So no error! you will get the output "Bicycle Implementation"
Originally posted by Ravindranath Chowdary: Why the below does not throw any compile time error. The Bicycle interface no where relates to Jchq class.
You must look with the compiler eyes on the code. All what the compiler knows is that you have a reference variable of type Jchq, which can hold an object of Jchq or any of its subclasses. Since the compiler doesn't know whether such subclasses exist and which interfaces they implement, he can't validate the cast.
In contrast, if you make Jchq final, the compiler knows that there are no subclasses and you get the expected error.
There are any number of checks a compiler could perform. In practice, only a limited number of them will be implemented. In this case the compiler's thinking could be "well, the developer told me to disregard what the object is, and to assume that it's a Bicycle, so that's what I'm going to do".
Yes, as Ulf said i too think that would be the way. Unless you insist the compiler to disregard the check by providing the explicist typecasting, it would definitely check and throw an error if in case of improper matches.