参照型の変換 - 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;
ランタイムエラー!
整数参照を文字列参照にキャストすることはできません。
Object o = 123; // o stores an Integer
Float s2 = (Float) o;
ランタイムエラー!
Integer 参照を Float 参照にキャストすることはできません。
Object o = 123f; // o stores a Float
Float s2 = (Float) o;
同じ型に変換します。縮小参照変換。

"参照変換の拡大または縮小は、オブジェクトをまったく変更しません。縮小 (または拡大) 部分は、代入操作に変数とその新しい値の型チェックが含まれる (含まれない) という事実を具体的に指します。 」

「これはすべてが明らかな珍しい例です。」

"これらの例のエラーを回避するために、 オブジェクト変数によってどの型が参照されているかを確認する方法があります。 "

コード
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;
}
3
タスク
Java Syntax,  レベル 10レッスン 6
ロック未解除
Code entry
Your attention, please! Now recruiting code entry personnel for CodeGym. So turn up your focus, let your fingers relax, read the code, and then... type it into the appropriate box. Code entry is far from a useless exercise, though it might seem so at first glance: it allows a beginner to get used to and remember syntax (modern IDEs seldom make this possible).

「オブジェクトのタイプを 100% 確信している場合を除き、すべての拡張変換の前にこのチェックを実行する必要があります。」

"とった。"