Casting variables in Java

前端 未结 5 1659
野性不改
野性不改 2020-11-21 23:50

I wonder if anyone could tell me how casting works? I understand when I should do it, but not really how it works. On primitive data types I understand partially bu

5条回答
  •  感情败类
    2020-11-22 00:33

    Suppose you wanted to cast a String to a File (yes it does not make any sense), you cannot cast it directly because the File class is not a child and not a parent of the String class (and the compiler complains).

    But you could cast your String to Object, because a String is an Object (Object is parent). Then you could cast this object to a File, because a File is an Object.

    So all you operations are 'legal' from a typing point of view at compile time, but it does not mean that it will work at runtime !

    File f = (File)(Object) "Stupid cast";
    

    The compiler will allow this even if it does not make sense, but it will crash at runtime with this exception:

    Exception in thread "main" java.lang.ClassCastException:
        java.lang.String cannot be cast to java.io.File
    

提交回复
热议问题