引用類型轉換 - 1

“現在,來自 Diego 的簡短課程。簡明扼要。關於引用類型轉換。”

“讓我們從對像變量開始。您可以將任何引用類型分配給這樣的變量(擴大轉換)。但是,要在另一個方向(縮小轉換)進行分配,您必須明確指示強制轉換操作:”

代碼 描述
String s = "mom";
Object o = s; // o stores a String
典型的 擴大參考轉換
Object o = "mom"; // o stores a String
String s2 = (String) o;
典型的窄化參考轉換
Integer i = 123; // o stores an Integer
Object o = i;
拓寬轉化。
Object o = 123; // o stores an Integer
String s2 = (String) o;
運行時錯誤!
您不能將 Integer 引用轉換為 String 引用。
Object o = 123; // o stores an Integer
Float s2 = (Float) o;
運行時錯誤!
您不能將 Integer 引用轉換為 Float 引用。
Object o = 123f; // o stores a Float
Float s2 = (Float) o;
轉換為相同類型。縮小參考轉換。

"擴大或縮小引用轉換不會以任何方式更改對象。縮小(或擴大)部分具體指的是賦值操作包括(不包括)變量及其新值的類型檢查。 “

“這是罕見的一切都清楚的例子。”

“為了避免這些示例中的錯誤, 我們有一種方法可以找出 Object 變量引用的類型:

代碼
int i = 5;
float f = 444.23f;
String s = "17";
Object o = f;                       // o stores a Float

if (o instanceof  Integer)
{
    Integer i2 = (Integer) o;
}
else if (o instanceof  Float)
{
    Float f2 = (Float) o;            // This if block will be executed
}
else if (o instanceof  String)
{
    String s2 = (String) o;
}

“除非您 100% 確定對象的類型,否則您應該在每次擴大轉換之前執行此檢查。”

“知道了。”