Cast reference of known type to an interface outside of type's hierarchy

后端 未结 6 1332
无人及你
无人及你 2021-01-20 11:44

Say you have a clean class like this:

public class A {
    // Stuff
}

And a interface like this:

public interface G {
    /         


        
6条回答
  •  渐次进展
    2021-01-20 12:14

    The issue here is that because G is an interface, it is possible that there is a subclass of A that implements G. Therefore it's at least possible that at runtime the type of the object stored in a implements G.

    "But I just assigned a to contain type A! Stupid compiler!" It's important to remember that when assessing the potential success of a cast, the compiler looks only at the compile-time type of the variable. As such, the compiler doesn't try to figure out what will actually be in the variable, it just looks at the type of the variable itself.

    Note that if you declare A to be final, then this becomes a compile-time error, since now the compiler knows there are no subclasses of A, and A itself doesn't implement G, and so the cast can never succeed at runtime.

    Finally, the same logic applies to casting C to A: C doesn't derive from A, and the compiler knows that no subclass of C derives from A (since they all derive from C at some point!) and so there's no possibility that the cast could succeed at runtime.

提交回复
热议问题