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

后端 未结 6 1342
无人及你
无人及你 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:15

    The compiler doesn't necessarily know whether or not a implements G or not.

    Casting pretty much tells the compiler to take this variable, and treat it like a different type.

    If you try to do an operation on the cast variable as though it implemented G(when it doesn't) you'll get a runtime error

提交回复
热议问题