Thomas Hauck wrote:Why does compilation for an unrelated interface succeed when using the 'instanceof' operator
but not for class?
For the code below in Example 1,
compiles even though reference variable 'c' has no relation to interface 'X'.
Thomas Hauck wrote:I wanted to generalize these results to determine if
Roel De Nijs wrote:
But this example compiles without any problem:
Reason why: the Number class is not final, so there could be a subclass that implements the Cloneable interface. That's also why (Cloneable) aNumber will compile (but will throw a ClassCastException at runtime).
Roel De Nijs wrote:
An example with 2 unrelated classes will always result in compiler error (similar to the 1st obvious example):
John Lerry wrote:The code compiles as the Number class is NOT final and then MAY (not sure that it does) implement the interface Cloneable but then a ClassCastException is throws because the JVM sees that the type of the object is an Integer that is a class final and therefore could not implement the interface Cloneable (type cast).
Is that correct?
John Lerry wrote:The code does not compile because the class Fish is not in the same class hierarchy Car.
Is that correct?
John Lerry wrote:I try to analyze this code. The code does not return an compile time error because the reference (n) is of type Number that is NOT a final class.
Not even return a runtime error because the object is of type MyCoolNumber that actually implements the interface Cloneable.
Therefore control on the type of class (so if final or not) occurs at compile time while the control on the implementation of interface (if it happens or not) occurs at runtime.
Is that correct?
John Lerry wrote:In general you can make a cast between a class and an interface if the class is NOT declared final, otherwise there will be an error in compilation.
John Lerry wrote:Also should be checked whether or not the class implements the interface.
John Lerry wrote:In the specific example the object is of type MyCoolNumber that implements the interface (Cloneable) then cast from MyCoolNumber to Cloneable not throw an exception at runtime.
When evil is afoot and you don't have any arms you gotta be hip and do the legwork, but always kick some ... tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
|