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

后端 未结 6 1322
无人及你
无人及你 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 11:58

    Casting correctness can only be checked at runtime. So in your example, even though it might be obvious to you, for the program it won't know it's incorrect until it's actually running and attempts to cast the variable a as the interface G. At this point it will throw a ClassCastException.

提交回复
热议问题