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
반응형
'즐거운프로그래밍' 카테고리의 다른 글
[자바] 인터페이스의 구현(interface) (1) | 2023.10.23 |
---|---|
[자바] Vector 클래스 (0) | 2023.10.17 |
[자바] extends, showInfo 문 활용한 예제 (0) | 2023.10.17 |
[자바] extends, insert 문 활용한 예제 (0) | 2023.10.17 |
[자바] 상속 extends와 private 함수를 사용한 예제 2 (0) | 2023.10.17 |