JAVA
31. 다형성
NamGH
2023. 8. 7. 22:25
다형성이란
하나의 메소드나 클래스가 있을 때 이것들이 다양한 방법으로 동작하는 것이다
다형성의 몇가지를 예로들면업캐스팅, 다운캐스팅메소드 오버라이딩 상속 클래스 등이 있다
class Robot{
}
class DanceRobot extends Robot{
void dance(){
System.out.println("춤을 춥시다.");
}
}
class SingRobot extends Robot{
void sing() {
System.out.println("노래를 합시다.");
}
}
class DrawRobot extends Robot{
void draw() {
System.out.println("그림을 그립시다.");
}
}
public class Ex13_다형성 {
public static void action(Robot r){
if(r instanceof DanceRobot) {
DanceRobot dr = (DanceRobot)r; // 다운캐스팅
dr.dance();
}else if(r instanceof SingRobot) {
SingRobot sr = (SingRobot)r; // 다운캐스팅
sr.sing();
}else if(r instanceof DrawRobot) {
DrawRobot dw = (DrawRobot)r; // 다운캐스팅
dw.draw();
}
}
public static void main(String[] args) {
Robot[] arr = {
new DanceRobot(),new SingRobot(),new DrawRobot()
};
int i;
for(i = 0; i < arr.length; i++) {
action(arr[i]);
}
}
}
다음 예시를 보면 부모 Robot에 DanceRobot, SingRobot, DrawRobot의 3명의 자식이 있다
instanceof란 true or false 로 알려주는 연산자이다
upcasting의 경우 자동으로 해주지면 downcasting의 경우 직접 입력해야하기때문에 다운 캐스팅의 경우에는 앞에 입력을 해준다
Robot 배열 arr을 만들어 각 자식들을 넣은뒤 조건문을 이용해 다운캐스팅일 경우만 출력되게 하였으며
다운캐스팅이기때문에 각각 앞에 (DanceRobot) (SingRobot) (DrawRobot)을 붙여줘야 정상 출력이 된다