简体   繁体   English

ClassCastException的真实示例

[英]Real World example of ClassCastException

I was asked in an interview to give an example of a ClassCastException for which I gave the below example 我在一次采访中被要求给出一个ClassCastException的示例,为此我给出了以下示例

class X{}
class Y extends X{}
class Z extends X{}
Y y=new Y();
Z z=new z();

(X)y is possible (X)z is possible (X)y是可能的(X)z是可能的

Z(y) and (Y)z will throw a ClassCastException. Z(y)(Y)z将引发ClassCastException。 Then the interview asked me to give real world example for which I said both boat and table are made up of wood 然后面试让我举一个真实的例子,我说船和桌子都是木头做的

table extends wood boat extends wood but you can not use table for fishing similarily you can not use table to sir or stand 桌子延伸木头船延伸木头,但是你不能用桌子类似地钓鱼,你不能用桌子来代替先生或站立

I want to know if my examples are right or not? 我想知道我的例子是否正确?

I would not have accepted that as an answer because a boat/table is not a subtype of wood. 我不会接受这作为答案,因为船/桌子不是木头的子类型。
A subtype of wood would be Oak or Cherry. 木材的一个子类型是橡木或樱桃木。

z = (Z)y will not throw a ClassCastException - it will never compile. z = (Z)y不会引发ClassCastException它永远不会编译。

The following will compile and throw a ClassCastException ( java.lang.ClassCastException: [LXXX$Y; cannot be cast to [LXXX$Z; ) on the second line 下面的代码将编译并抛出ClassCastException( java.lang.ClassCastException: [LXXX$Y; cannot be cast to [LXXX$Z;

    X[] xx = new Y[1];
    Z[] zz = (Z[]) xx;

In the same spirit 本着同样的精神

   Object obj  = new Integer(0);
   String str = (String) obj; // class cast exception here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM