Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | |||||
| 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| 10 | 11 | 12 | 13 | 14 | 15 | 16 |
| 17 | 18 | 19 | 20 | 21 | 22 | 23 |
| 24 | 25 | 26 | 27 | 28 | 29 | 30 |
| 31 |
Tags
- array
- Java
- spring boot
- side project
- tomcat
- Spring
- 개발자취업부트캠프
- github
- 패스트캠퍼스
- MVC 패턴
- MegabyteSchool
- 내일배움카드
- Interface
- Sts
- crud
- MVC
- 메가바이트스쿨
- 클래스 상속
- AWS
- group study
- 국비지원교육
- #javaStudy
- GIT
- #패스트캠퍼스 #국비지원교육 #메가바이트스쿨 #MegabyteSchool #개발자취업부트캠프 #내일배움카드
- Entity
- 게시판 리뷰 만들기
- 게시판 만들기
- View
- Algorism study
- 클래스 class
Archives
- Today
- Total
tuter77
Java : 다운 캐스팅, instanceOf 본문
▷DownCasting
- 업캐스팅 된 클래스를 다시 원래의 타입으로 형 변환
- 하위 클래스로의 형 변환은 명시적으로 해야한다.
예시) Customer vc = new VIPCustomer(); //묵시적
VIPCustomer vCustomer = (VIPCustomer)vc; //명시적
▷ instanceof 키워드
해당 instance의 타입을 확인해 인스턴의 형이 맞으면 true, 아니면 false를 반환한다.
예시)
Customer customerE = new GoldCustomer(10030, "Edward");
if(customerE instanceof GoldCustomer) {
GoldCustomer vc = (GoldCustomer)customerE;
System.out.println(customerE.showCustomerInfo());
}
위의 예시에서 보면 instanceof라는 키워드를 사용하여 customerE가 원래 GoldCustomer 인지를 확인한다.
다른 예시를 보면 아래와 같다.
//arraylist를 매개변수로 주어서 다운캐스팅하는 것 구현.
public void testDownCasting(ArrayList<Animal> list) {
for(int i=0; i<list.size(); i++) {
Animal animal = list.get(i);
if(animal instanceof Human) { //human 다운캐스팅
/*
* human 변수가 animal 타입에서 Human타입으로
* 다운캐스팅되어 하위클래스 고유 메서드를 사용할 수 있음.
*/
Human human = (Human)animal;
human.readBook();
}
else if(animal instanceof Tiger) {
Tiger tiger = (Tiger)animal;
tiger.hunting();
}
else if(animal instanceof Eagle) {
Eagle eagle = (Eagle)animal;
eagle.flying();
}
else {
System.out.println("unsupported type");
}
}
}
기존의 animal 예제에서 각 하위클래스 인스턴스들이 업캐스팅 되어있었는데(상위클래스 animal로) instanceof 키워드를 활용하여 다운캐스팅을 명시적으로 해놓은 코드이다.
인스턴스의 타입이 변했기 때문에 각 하위 클래스의 고유 메서드도 잘 사용되는것을 확인할 수 있다.
위 내용은 2023.01.06에 공부한 내용입니다.
'JavaStudy' 카테고리의 다른 글
| Java : 다형성 구현(DAO) (0) | 2023.01.29 |
|---|---|
| Java : 예외 처리 (0) | 2023.01.29 |
| Java : 상속(4) method overriding, 가상메서드, 다형성 (0) | 2023.01.29 |
| Java : 상속(3) super, 메모리, 업캐스팅 (0) | 2023.01.29 |
| Java : 상속(2) 및 복습. (0) | 2023.01.29 |