본문 바로가기

JAVA

java #문제풀기 4 상속

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 사용예