Casting variables in Java

前端 未结 5 1675
野性不改
野性不改 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 00:28

    Casting a reference will only work if it's an instanceof that type. You can't cast random references. Also, you need to read more on Casting Objects.

    e.g.

    String string = "String";
    
    Object object = string; // Perfectly fine since String is an Object
    
    String newString = (String)object; // This only works because the `reference` object is pointing to a valid String object.
    

提交回复
热议问题