การแปลงประเภทการอ้างอิง - 1

"และตอนนี้ บทเรียนสั้นๆ จากดิเอโก สั้นและตรงประเด็น เกี่ยวกับการแปลงประเภทการอ้างอิง"

"เรามาเริ่มกันที่ตัวแปร Object คุณสามารถกำหนดประเภทการอ้างอิงใดๆ ให้กับตัวแปรดังกล่าว ( การแปลงที่กว้างขึ้น ) อย่างไรก็ตาม เพื่อให้การกำหนดไปในทิศทางอื่น ( การแปลงที่แคบลง ) คุณต้องระบุการดำเนินการส่งอย่างชัดเจน:"

รหัส คำอธิบาย
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;
การทำงานผิดพลาด!
คุณไม่สามารถส่งการอ้างอิงจำนวนเต็มไปยังการอ้างอิงแบบลอยตัว
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;
}
3
งาน
Java Syntax,  ระดับบทเรียน
ล็อค
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% เกี่ยวกับประเภทของวัตถุ"

"เข้าใจแล้ว."