반응형
SMALL
class Animal {
public void move() {
System.out.println("동물이 움직입니다.");
}
}
class Human extends Animal {
public void move() {
System.out.println("사람이 두발로 걷습니다.");
}
public void readBook() {
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("독수리가 하늘을 날아갑니다.");
}
}
public class AnimalTest {
public static void main(String [] args) {
AnimalTest test = new AnimalTest();
test.moveAnimal(new Human());
test.moveAnimal(new Tiger());
test.moveAnimal(new Eagle());
}
public void moveAnimal(Animal animal) {
animal.move();
// 다운 캐스팅
if(animal instanceof 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("지원되지 않는 기능입니다.");
}
}
}
- 'instanceof'를 이용한다.
- 상속을 하더라도, 해당 클래스만 가지고 있는 메서드를 사용하고 싶을 때 사용한다.
- 오버라이딩을 쓸 수 있으면 좋지만, 쓸 수 없으면 다운캐스팅 사용.
cf. do it 자바 인프런 강의
반응형
LIST
'JAVA' 카테고리의 다른 글
[JAVA] String vs StringBuilder (0) | 2023.07.05 |
---|---|
[JAVA] 템플릿 메서드 (0) | 2022.03.31 |
[JAVA] 다형성 (Polymorphism) (0) | 2022.03.24 |
[JAVA] 가상 메서드 (0) | 2022.03.24 |
[JAVA] 상위 클래스로 묵시적 형변환 (업캐스팅) (0) | 2022.03.24 |
댓글