BackEnd/JAVA

5-1. 상속 연습 예제 - 네비게이션

BlancPong 2022. 2. 22. 12:26
728x90

- 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.java

public 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.java

public class ButtonSports extends Button {
    public ButtonSports() {
        super("Sports");
    }
    
    public void onClick() {
        System.out.println(this.GetCategory() + " Button Click");
    }
}


- Navigation.java

public 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.java

public 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