객체 지향 프로그램 예제 1
작성자 정보
- 작성자 최고관리자
- 작성일
컨텐츠 정보
- 조회 327
본문
//Hero.java --------------------------------------------------------------------------------
public class Hero {
public static Object length;
String name;
public Hero(String name) {
this.name = name;
}
public void attack() {
System.out.println("주먹찌르기");
}
}
//Archer.java --------------------------------------------------------------------------------
public class Archer extends Hero {
public Archer(String name) {
super(name);
}
public void fireArrow() {
System.out.println("불화살!");
}
}
//Warrior.java --------------------------------------------------------------------------------
public class Warrior extends Hero { //상속
public Warrior(String name) {
super(name);
}
public void groundCutting() {
System.out.println("대지 가르기");
}
}
//Wizard.java --------------------------------------------------------------------------------
public class Wizard extends Hero {
public Wizard(String name) {
super(name);
}
public void freezing() {
System.out.println("얼리비!");
}
}
//Main.java --------------------------------------------------------------------------------
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Hero[] heros = new Hero[3];
heros[0] = new Warrior("전사"); // 다형성
heros[1] = new Archer("궁수");
heros[2] = new Wizard("마법사");
for (int i = 0; i<heros.length; i++) {
heros[i].attack();
if(heros[i] instanceof Warrior) {
Warrior temp = (Warrior) heros[i]; // 잠재적 Object 상속
temp.groundCutting();
} else if (heros[i] instanceof Archer) {
Archer temp = (Archer) heros[i];
temp.fireArrow();
} else if (heros[i] instanceof Wizard) {
Wizard temp = (Wizard) heros[i];
temp.freezing();
}
}
}
}
관련자료
-
이전
-
다음
댓글 0개
등록된 댓글이 없습니다.