原理请参考Java Language Specification:Reference Type Casting 中有关引用类型转换的表述,其中相关部分为:Given a compile-time reference type S (source) and a compile-time reference type T (target), a casting conversion exists from S to T if no compile-time errors occur due to the following rules.
If S is a class type:
•If T is a class type, then either |S| <: or otherwise a compile-time error occurs.>
Furthermore, if there exists a supertype X of T, and a supertype Y of S, such that both X and Y are provably distinct parameterized types (§4.5), and that the erasures of X and Y are the same, a compile-time error occurs.
满足|S| <: or casts and unchecked at run time r is an ordinary class array>
•If T is a class type, then R must be either the same class (§4.3.4) as T or a subclass of T, or a run-time exception is thrown.
因为Container和JComponent之间存在着父子关系,所以根据Java语言规范,保证了他们之间的转换在编译期不会报错,但是具体getContentPane方法的返回值的runtime类型是否满足上述条件,则需要在运行时进行类型检查。具体在VM的实现上,是根据checkcast这个字节码指令来完成的,相关解释规则可以参见JVM规范:Chapter 6. The Java Virtual Machine Instruction Set。