타입 캐스팅 Java에서 는 한 유형의 객체 또는 변수를 다른 유형으로 변환하는 데 사용됩니다. 한 데이터 유형을 다른 데이터 유형으로 변환하거나 할당할 때 호환되지 않을 수 있습니다. 적합하면 원활하게 수행되지 않으면 데이터 손실 가능성이 있습니다.
자바의 유형 캐스팅 유형
Java Type 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
캐스팅 축소(큰 유형에서 작은 유형으로)
더 큰 유형을 더 작은 유형에 할당할 때 명시적 캐스팅 필수입니다.
예시 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