public class ElvesTest {
public static void main(String[] args) {
// 엘프 객체 생성 & 업캐스팅(부모 타입으로 해석)
Elf a = new Elf("티란데", 100);
HighElf b = new HighElf("알퓨리온", 160, 100);
ElfLoad c = new ElfLoad("마이에브", 230, 140, 100);
}
class Elf {
protected String name;
protected int hp;
public Elf(String name, int hp) {
this.name = name;
this.hp = hp;
}
...
}
class HighElf extends Elf {
protected int mp;
public HighElf(String name, int hp, int mp) {
super(name, hp); // 부모 클래스 생성자 호출;
this.mp = mp;
}
...
}
class ElfLoad extends HighElf {
protected int sh;
public ElfLoad(String name, int hp, int mp, int sh) {
super(name, hp, mp, sh); // 부모 클래스 생성자 호출;
this.sh = sh;
}
...
}
}
public class ElvesTest {
public static void main(String[] args) {
// 엘프 객체 생성 & 업캐스팅
Elf a = new Elf("티란데", 100);
Elf b = new HighElf("알퓨리온", 160, 100);
Elf c = new ElfLoad("마이에브", 230, 140, 100);
// ArrayList로 묶기!
ArrayList<Elf> list = new ArrayList<Elf>();
list.add(a);
list.add(b);
list.add(c);
// 반복을 통한 출력!
for (int i; i < list.size(); i++) {
System.out.println(list.get(i).toString());
}
}
class Elf {
...
public String toString() {
return String.format("[엘프] Name: %s, HP: %d", name, hp);
}
}
class HighElf extends Elf {
...
// 메소드 오버라이딩
public String toString() {
return String.format("[하이엘프] Name: %s, HP: %d, MP: %d", name, hp, mp);
}
}
class Elf {
...
// 메소드 오버라이딩
public String toString() {
return String.format("[하이엘프] Name: %s, HP: %d, MP: %d, SH: %d", name, hp, mp, sh);
}
}
}