-
5-1. 상속 연습 예제 - 네비게이션BackEnd/JAVA 2022. 2. 22. 12:26728x90
- Button.java
public abstract class Button { // -- Fields private String category = ""; // 색상같은 객체가 관리해야 하는 정보를 추가 // -- Getter public String GetCategory() { return category; } // -- Constructor public Button(String _category) { this.category = _category; } // -- Methods // 함수가 정의되지 않은 추상 클래스는 객체 생성 불가 public abstract void onClick(); }
- ButtonNews.javapublic class ButtonNews extends Button { // 이미 카테고리가 확정이기 때문에 추가로 처리할 필요 없음 // new ButtonNews("News"); //public ButtonNews(String _category) {} public ButtonNews() { //this.category = "News"; super("News"); } public void onClick() { System.out.println(this.GetCategory() + " Button Click"); } }
- ButtonSports.javapublic class ButtonSports extends Button { public ButtonSports() { super("Sports"); } public void onClick() { System.out.println(this.GetCategory() + " Button Click"); } }
- Navigation.javapublic class Navigation { // -- Fields private int btnWidth = 100; // 버튼 폭 private int btnHeight = 40; // 버튼 높이 private Button btns[] = new Button[5]; // -- Methods public void addButton(int _idx, Button _btn) { if (_idx < 0 || _idx >= btns.length) return; // Garbage Collection btns[_idx] = _btn; } // TODO: 추가기능 // 1. 버튼 배열에서 빈 칸에 버튼을 추가 // 2. 빈 칸이 없는 경우 실패 public void printAll() { for (int i = 0; i < btns.length; ++i) { if (btns[i] != null) System.out.println( (i + 1) + ": " + btns[i].GetCategory()); } } public void onClickButton(int _idx) { if (btns[_idx] != null) btns[_idx].onClick(); } }
- HelloJava.javapublic class HelloJava { public static void main(String[] args) { Navigation nav = new Navigation(); nav.addButton(1, new ButtonNews()); nav.addButton(3, new ButtonSports()); nav.printAll(); nav.onClickButton(1); } // main } // class
'BackEnd > JAVA' 카테고리의 다른 글
For 문의 연습 (0) 2022.03.28 6. MyArrayList (0) 2022.02.23 5. 상속(Inheritance) (0) 2022.02.21 4. 배열(Array) (0) 2022.02.18 3. 정적 Static (0) 2022.02.18