What makes an object assignment-compatible with another class?

前端 未结 5 1343
借酒劲吻你
借酒劲吻你 2021-01-15 01:43

I\'m wondering what specifically allows an object of one class to be cast as another class. Looking at the Class.isInstance(Object obj) javadoc, it suggests that an object

5条回答
  •  醉梦人生
    2021-01-15 02:27

    Consider these two cases:

    A a = new B();
    B b = (B)a;    <--  Ok.
    
    A a = new A();
    B b = (B)a;    <--  ClassCastException
    

    So in order to cast an object to B it must be an instance of B (or a subclass of B).

    In your case it is however an instance of A.

提交回复
热议问题