Type casting ใน Java ใช้แปลงออบเจ็กต์หรือตัวแปรของชนิดหนึ่งเป็นอีกชนิดหนึ่ง เมื่อแปลงหรือกำหนดชนิดข้อมูลหนึ่งเป็นอีกชนิดหนึ่ง อาจจะไม่ compatible หากเหมาะสมจะทำได้อย่างราบรื่น แต่ถ้าไม่เหมาะสมจะมีโอกาสสูญเสียข้อมูล (data loss)
ประเภทของ Type Casting ใน Java
Java Type Casting แบ่งเป็น 2 ประเภท:
- Widening Casting (Implicit) – Automatic Type Conversion
- Narrowing Casting (Explicit) – ต้องการ Explicit Conversion
Widening Casting (ชนิดเล็กไปชนิดใหญ่)
Widening Type Conversion เกิดขึ้นได้ถ้าทั้งสองชนิด compatible และ target type ใหญ่กว่า source type Widening Casting เกิดขึ้นเมื่อ สองชนิด compatible และ target type ใหญ่กว่า source type
ตัวอย่างที่ 1
public class ImplicitCastingExample {
public static void main(String args[]) {
byte i = 40;
// No casting needed for below conversion
short j = i;
int k = j;
long l = k;
float m = l;
double n = m;
System.out.println("byte value : "+i);
System.out.println("short value : "+j);
System.out.println("int value : "+k);
System.out.println("long value : "+l);
System.out.println("float value : "+m);
System.out.println("double value : "+n);
}
}
ผลลัพธ์
byte value : 40 short value : 40 int value : 40 long value : 40 float value : 40.0 double value : 40.0
Widening Casting ของ Class Type
ในตัวอย่างด้านล่าง Child class เป็นชนิดเล็ก เรากำหนดให้เป็น Parent class type ซึ่งเป็นชนิดใหญ่กว่า จึงไม่ต้อง cast
ตัวอย่างที่ 2
class Parent {
public void display() {
System.out.println("Parent class display() called");
}
}
public class Child extends Parent {
public static void main(String args[]) {
Parent p = new Child();
p.display();
}
}
ผลลัพธ์
Parent class display() method called
Narrowing Casting (ชนิดใหญ่ไปชนิดเล็ก)
เมื่อเรากำหนดชนิดใหญ่ให้ชนิดเล็ก Explicit Casting จำเป็นต้องใช้
ตัวอย่างที่ 1
public class ExplicitCastingExample {
public static void main(String args[]) {
double d = 30.0;
// Explicit casting is needed for below conversion
float f = (float) d;
long l = (long) f;
int i = (int) l;
short s = (short) i;
byte b = (byte) s;
System.out.println("double value : "+d);
System.out.println("float value : "+f);
System.out.println("long value : "+l);
System.out.println("int value : "+i);
System.out.println("short value : "+s);
System.out.println("byte value : "+b);
}
}
ผลลัพธ์
double value : 30.0 float value : 30.0 long value : 30 int value : 30 short value : 30 byte value : 30
Narrowing ของ Class Type
เมื่อเรากำหนดชนิดใหญ่ให้ชนิดเล็ก เราต้อง explicitly typecast
ตัวอย่างที่ 2
class Parent {
public void display() {
System.out.println("Parent class display() method called");
}
}
public class Child extends Parent {
public void display() {
System.out.println("Child class display() method called");
}
public static void main(String args[]) {
Parent p = new Child();
Child c = (Child) p;
c.display();
}
}
ผลลัพธ์
Child class display() method called