티스토리 뷰

반응형

⊙ 문제

 

다음 표를 참고해 Phone, Phone의 자식 클래스 Telephone, Telephone의 자식 클래스 Smartphone을 작성하고, 테스트 프로그램도 작성하시오.

 

 

Phone

Telephone

Smartphone

필드

protected String owner

private String when

private String game

메서드

void talk()

void autoAnswering()

void playGame()

 

  1. 각 클래스에 모든 필드를 초기화하는 생성자를 추가한다.
  2. 각 클래스의 메서드를 구현한다. talk()는 owner가 통화 중, autoAnswering()은 owner가 부재중이니 when에 전화 요망, playGame()은 owner가 game 게임 중이라는 메시지를 출력한다.
  3. Phone, Telephone, Smartphone 객체로 Phone 타입 변수에 대입한다. 그리고 반복문과 조건문으로 실제 타입을 조사한 후 Phone 타입이면 talk(), Telephone 타입이면 autoAnswering(), Smartphone 타입이면 playGame()을 호출한다.

 

public class PhoneTest {
    public static void main(String[] args) {
        Phone[] phones = { new Phone("황진이"), new Telephone("길동이", "내일"), new Smartphone("민국이", "갤러그") };

        //코드추가

        
    }

}

 

⊙ 문제 접근 과정

 

조건 그대로 순서대로 차근차근 하자

 

 


 

⊙ 문제 풀이

 

class Phone {
    protected String owner;
    Phone(String owner) {
        this.owner = owner;
    }
    void talk() {
        System.out.println(owner + "가 통화 중이다.");
    }
}

class Telephone extends Phone {
    private String when;
    Telephone(String owner, String when) {
        super(owner);
        this.when = when;
    }
    void autoAnswering() {
        System.out.println(owner + "가 없다. " + when + "전화 줄래.");
    }
}

class Smartphone extends Telephone {
    private String game;
    Smartphone(String owner, String game) {
        super(owner,"when");
        this.game = game;
    }
    void playGame() {
        System.out.println(owner + "가 " + game + " 게임을 하는 중이다.");
    }
}

public class PhoneTest {
    public static void main(String[] args) {
        Phone[] phones = { new Phone("황진이"), new Telephone("길동이", "내일"), new Smartphone("민국이", "갤러그") };

        for (Phone phone : phones) {
            if (phone instanceof Smartphone) {
                ((Smartphone) phone).playGame();
            } else if (phone instanceof Telephone) {
                ((Telephone) phone).autoAnswering();
            } else if (phone instanceof Phone) {
                phone.talk();
            }

        }
    }

}

 

 


⊙ 결과

 


⊙ 마무리

 

NONE

 

좋아요 로그인하지 않아도 누를 수 있습니다!

 

728x90
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함