형변환(캐스팅)
- 하나의 데이터 타입을 다른 타입으로 바꾸는 것
- 자바의 데이터형
- 기본형(primitive type) : boolean, short, int, long, float, double, char
- 참조형(reference type) : class, interface, array, enum, ...
- 대입 연산자 '=' 에서 변수와 값 서로 양쪽의 타입이 일치하지 않으면 할당 불가능
int i = 10.2;
int i = (int)10.2;
- 상속 관계에 있는 부모와 자식 클래스 간에는 서로 간의 형변환 가능
- 형제 클래스끼리는 아예 타입이 다르기 때문에 참조 형변환 불가능

class Fruit {
String name;
int count;
}
class Apple extends Fruit {
String color;
}
Fruit f = new Fruit();
Apple a = new Apple();
Melon m = new Melon();
Fruit f2 = (Fruit) a2;
Apple a2 = (Apple) f2;
업캐스팅
- 자식 클래스가 부모 클래스 타입으로 캐스팅
- 캐스팅 연산자 괄호 생략 가능
- 업캐스팅 후 메서드 실행 시 만약 자식 클래스에서 오버라이딩 한 메서드가 있을 경우, 오버라이딩 된 메서드가 실행
- 사용 이유 : 공통적으로 할 수 있는 부분을 만들어 간단하게 다루기 위해(하나의 인스턴스로 묶어서 관리 가능)
class Animal {
public void cry() {
System.out.prinln("동물이 웁니다.");
}
}
class Dog extends Animal {
public void bark() {
System.out.prinln("멍멍");
}
public void run() {
System.out.println("호다닥");
}
}
public class Main {
public static void main(String[] args) }
Animal animal;
Dog dog = new Dog();
animal = (Animal) dog;
animal = dog;
}
}
다운캐스팅
- 부모 클래스가 자식 클래스 타입으로 캐스팅
- 캐스팅 연산자 괄호 생략 불가능
- 목적 : 업캐스팅한 객체를 다시 자식 클래스 타입의 객체로 되돌리는데 목적(복구)
class Animal {
public void cry() {
System.out.prinln("동물이 웁니다.");
}
}
class Dog extends Animal {
public void bark() {
System.out.prinln("멍멍");
}
public void run() {
System.out.println("호다닥");
}
}
public class Main {
public static void main(String[] args) {
Animal animal;
Dog dog = new Dog();
animal = dog;
Dog dog2 = (Dog) animal;
dog2.bark();
dog2.run();
}
}