05. 다음 표를 참고해 Phone, Phone의 자식 클래스 Telephone, Telephone의 자식 클래스 Smartphone을 작성하고, 테스트 프로그램도 작성하시오.
class Phone {
protected String owner;
public Phone(String owner) {
super(); // 자주 까먹고 안씀 꼭 쓸것!!
this.owner = owner;
}
void talk() {
System.out.println(owner + "가 통화 중이다.");
}
}
class Telephone extends Phone {
private String when;
public Telephone(String owner, String when) {
super(owner); // 자주 까먹고 안씀 꼭 쓸것!!
this.when = when;
}
void autoAnswering() {
System.out.println(owner + "가 부재 중이다." + when + " 전화 줄래.");
}
}
class Smartphone extends Telephone {
private String game;
public Smartphone(String owner, String color, String game) {
super(owner, color); // 자주 까먹고 안씀 꼭 쓸것!!
this.game = game;
}
void playGame() {
System.out.println(owner + "가 " + game + " 게임을 하는 중이다.");
}
}
public class PTest05 {
public static void main(String[] args) {
Phone[] phones = { new Phone("황진이"), new Telephone("길동이", "내일"), new Smartphone("민국이", "빨간색", "갤러그") };
for (Phone p : phones) {
if (p instanceof Smartphone)
((Smartphone) p).playGame();
else if (p instanceof Telephone)
((Telephone) p).autoAnswering();
else
p.talk();
}
}
}
자주하는 실수: super() 까먹기... 까먹지 말자!!!!
몰랐던 개념: 조건문 instanceof 연산자
레퍼런스가 가리키는 객체의 타입 식별을 위해 사용
사용법
instanceof 사용예
'JAVA' 카테고리의 다른 글
java #8 내부 클래스와 익명 클래스 , try-catch, 예외 발생시키기 (0) | 2021.05.12 |
---|---|
java #7 디폴트 메서드와 static 메서드, 추상 클래스와 인터페이스(복습) (0) | 2021.05.11 |
java #문제풀기3 상속문제 (0) | 2021.05.06 |
java #6 인터페이스 (0) | 2021.05.04 |
java #5 상속(업캐스팅, 다운캐스팅, intanceof, 오버라이딩, 추상메소드) (0) | 2021.05.03 |