int num = 10.0; // error
10.0이라는 데이터가 num 변수에 들어가면 데이터의 손실이 발생하므로,
이것을 막고자 컴파일 에러가 발생 됨
int num = (int)10.0; // num=10
만약 프로그래머가 데이터가 손실 된다는 것을 이미 알고,
OOP의 다형성을 이용하고 싶을 때 위와 같이 캐스팅을 사용
실제 데이터 앞에 (데이터의 자료형)을 붙여주면 캐스팅이 됨
double b = 1; // b=1.0
묵시적 형변환 (캐스팅이 자동적으로 발생)
상속 관계의 부모 클래스와 자식 클래스 간의 형변환에 사용 됨
자식 클래스에서 부모 클래스로 형 변환 하는 것을 의미
(= 하위 클래스에서 상위 클래스로 형 변환)
다형성을 활용하기 위해 사용
public class Person {...}
public class Student extends Person {...}
Person human = new Student(); // UpCasting
// 아래와 같이 명시적으로 타입 캐스팅 선언을 하지 않아도 된다.
// Person person = (Person) new student;
class Animal {
public void move() {
System.out.println("동물이 움직입니다.");
}
}
class Human extends Animal {
public void move() {
System.out.println("사람이 두발로 걷습니다.");
}
public void readBooks() {
System.out.println("사람이 책을 읽습니다.");
}
}
class Tiger extends Animal {
public void move() {
System.out.println("호랑이가 네 발로 뜁니다.");
}
public void hunting() {
System.out.println("호랑이가 사냥을 합니다.");
}
}
class Eagle extends Animal {
public void move() {
System.out.println("독수리가 하늘을 날아갑니다.");
}
public void flying() {
System.out.println("독수리가 날개를 쭉 펴고 멀리 날아갑니다.");
}
}
Animal hAnimal = new Human();
Animal tAnimal = new Tiger();
Animal eAnimal = new Eagle();
hAnimal.move();
tAnimal.move();
eAnimal.move();
명시적 형변환 (캐스팅 할 내용을 적어줘야 함)
업캐스팅 한 것을 다시 원래의 형으로 복원 시키는 것
⇒ 따라서 원래의 형을 꼭 명시 해줘야 한다
부모 클래스가 자식 클래스 타입으로 캐스팅 되는 것
자식 자료형의 고유 기능을 사용하고 싶을 때 DownCasting 사용
public class Person {...}
public class Student extends Person {...}
Person human= new Student(); // 업캐스팅
Student gilDong = (Student)human; // 다운캐스팅
참고 블로그 :
https://sundrystore.tistory.com/17
https://mommoo.tistory.com/41
https://mommoo.tistory.com/51