A การหล่อแบบ ใน Java ใช้เพื่อแปลงวัตถุหรือตัวแปรประเภทหนึ่งเป็นอีกประเภทหนึ่ง เมื่อเรากำลังแปลงหรือกำหนดประเภทข้อมูลหนึ่งไปยังอีกประเภทหนึ่ง ข้อมูลเหล่านั้นอาจเข้ากันไม่ได้ หากเหมาะสมก็จะทำได้อย่างราบรื่นไม่เช่นนั้นข้อมูลจะสูญหาย
พิมพ์ประเภทการแคสต์ใน Java
Java Type Casting แบ่งออกเป็น 2 ประเภท
- ขยายการหล่อ (โดยนัย ) – การแปลงประเภทอัตโนมัติ
- จำกัดการแคสต์ (โจ่งแจ้ง ) – ต้องการการแปลงที่ชัดเจน
การหล่อแบบขยาย (แบบเล็กไปใหญ่)
ขยาย ท ype Conversion อาจเกิดขึ้นได้หากทั้งสองประเภทเข้ากันได้และประเภทเป้าหมายมีขนาดใหญ่กว่าประเภทต้นทาง Widening Casting เกิดขึ้นเมื่อสองประเภทเข้ากันได้ และ ประเภทเป้าหมายนั้นใหญ่กว่าประเภทต้นทาง .
ตัวอย่าง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
การขยายขอบเขตของประเภทคลาส
ในตัวอย่างด้านล่าง ลูก class เป็นประเภทที่เล็กกว่าที่เรากำหนดให้ ผู้ปกครอง ประเภทคลาสซึ่งเป็นประเภทที่ใหญ่กว่าจึงไม่จำเป็นต้องทำการหล่อ
ตัวอย่าง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
การหล่อแบบแคบ (แบบใหญ่ไปเล็ก)
เมื่อเรากำหนดประเภทที่ใหญ่กว่าให้กับประเภทที่เล็กกว่า 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
การจำกัดประเภทคลาสให้แคบลง
เมื่อเรากำหนดประเภทที่ใหญ่กว่าให้กับประเภทที่เล็กกว่า เราต้องอย่างชัดเจน พิมพ์ดีด มัน.
ตัวอย่าง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