즐거운프로그래밍

[자바] extends 문 활용한 예제 (Game)

수수께끼 고양이 2023. 10. 17. 17:57
728x90
반응형

 

1. 메인 클래스

public class Main {
    public static void main(String[] args) {
        Worrior worrior = new Worrior();
        Sword sword = new Sword();
        worrior.take(sword); // Weapon weapon=sword
        worrior.attack();
        Cane cane = new Cane();
        worrior.take(cane); //  Weapon weapon=cane
        worrior.attack();
    }
}

 

2. 워리어 클래스

class Worrior {
    Weapon weapon;
    void take(Weapon weapon) {
        this.weapon=weapon;
    }
    void attack() {
        weapon.use();
    }
}

 

3. 무기 클래스

class Weapon {
    void use() {
        System.out.println("무기를 사용하다.");
    }
}

 

4. 세부 무기 클래스

class Sword extends Weapon {
    void use() {
        System.out.println("검을 사용하다.");
    }
}
class Cane extends Weapon {
    void use() {
        System.out.println("지팡이를 사용하다.");
    }
}

 

 

728x90
반응형