7-11 문제 7-10에서 작성한 MyTv2 클래스에 이전 채널(previous channel)로 이동하는 기능의 메서드를 추가해서 실행결과와 같은 결과를 얻도록 하시오.

이전 채널의 값을 저장할 멤버변수를 정의하라.

 

메서드명 : gotoPrevChannel

기     능 : 현재 채널을 이전 채널로 변경한다.

반환 타입 : 없음

매개변수 : 없음

class MyTv2 {
	boolean isPowerOn;
	int channel;
	int volume;
	int prechannel;
	final int MAX_VOLUME = 100;
	final int MIN_VOLUME = 0;
	final int MAX_CHANNEL = 100;
	final int MIN_CHANNEL = 1;

	public void setVolume(int volume) {
		if (volume > MAX_VOLUME || volume < MIN_VOLUME)
			return;
		this.volume = volume;
		
	}

	public int getVolume() {
		return volume;
	}

	public void setChannel(int channel) {
		if (channel > MAX_CHANNEL || channel < MIN_CHANNEL)
			return;
		prechannel = this.channel;
		this.channel = channel;
	}

	public int getChannel() {
		return channel;
	}
	
	public void gotoPrevChannel() {
		setChannel(prechannel);
	}
	
}

class ExerciseEx7_11 {
	public static void main(String args[]) {
		MyTv2 t = new MyTv2();
		t.setChannel(10);
		System.out.println("CH:"+t.getChannel());
		t.setChannel(20);
		System.out.println("CH:"+t.getChannel());
		t.gotoPrevChannel();
		System.out.println("CH:"+t.getChannel());
		t.gotoPrevChannel();
		System.out.println("CH:"+t.getChannel());

	}
}

 

 

 

7-12 다음 중 접근 제어자에 대한 설명으로 옳지 않은 것은?(모두 고르시오) c

a. public은 접근 제한이 전혀 없는 접근 제어 자이다.

b. (default)가 붙으면, 같은 패키지 내에서만 접근이 가능하다.

c. 지역변수에도 접근제어자를 사용할 수 있다.

d. protect가 붙으면, 같은 패키지 내에서도 접근이 가능하다.

e. protected가 붙으면, 다른 패키지의 자손 클래스에서 접근이 가능하다.

 

c. 지역변수에는 접근제어자를 사용할 수 없다.

 

 

 

7-13 Math클래스의 생성자는 접근 제어자가 private이다. 그 이유는 무엇인가?

Math클래스의 모든 메서드가 static메서드이고 인스턴스 변수가 존재하지 않기 때문에 객체를 생성할 필요가 없기 때문이다.

 

 

 

7-14 문제 7-1에 나오는 섰다 카드의 숫자와 종류(isKwang)는 사실 한번 값이 지정되면 변경되어서는 안 되는 값이다. 카드 숫자가 한번 잘못 바뀌면 똑같은 카드가 두장이 될 수도 있기 때문이다. 이러한 문제점이 발생하지 않도록 아래의 SutdaCard를 수정하시오.

class SutdaCard {
	final int num;
	final boolean isKwang;

	SutdaCard() {
		this(1, true);
	}

	SutdaCard(int num, boolean isKwang) {
		this.num = num;
		this.isKwang = isKwang;
	}

	public String toString() {
		return num + (isKwang ? "K" : "");
	}
}

class Exercise7_14 {
	public static void main(String args[]) {
		SutdaCard card = new SutdaCard(1, true);
	}
}

 

 

 

 

7-15 클래스가 다음과 같이 정의되어 있을 때, 형 변환을 올바르게 하지 않은 것은? e

	class Unit {}
	class AirUnit extends Unit {}
	class GroundUnit extends Unit {}
	class Tank extends GroundUnit {}
	class AirCraft extends AirUnit {}
	Unit u = new GroundUnit();
	Tank t = new Tank();
	AirCraft ac = new AirCraft();

a. u = (Unit) ac;

b. u = ac;

c. GroundUnit gu = (GroundUnit) u;

d. AirUnit au = ac;

e. t = (Tank) u;

f. GroundUnit gu = t;

 

e. 조상 타입의 인스턴스를 자손 타입으로 형 변환할 수 없다.

 

 

7-16 다음 중 연산 결과가 true가 아닌 것은? (모두 고르시오) e

	class Car {}
	class FireEngine extends Car implements Movable {}
	class Ambulance extends Car {}
	FireEngine fe = new FireEngine()

a. fe instanceof FireEngine

b. fe instanceof Movable

c. fe instanceof Object

d. fe instanceof Car

e. fe instanceof Ambulance

 

e Abulance는 FireEngine과 아무 관계도 없다.

 

 

7-17 아래 세 개의 클래스로부터 공통부분을 뽑아서 Unit이라는 클래스를 만들고, 이 클래스를 상속받도록 코드를 변경하시오.

class Marine { // 보병
	int x, y; // 현재 위치
	void move(int x, int y) { /* */ } //지정된 위치로 이동
	void stop() { /* */ } //현재 위치에 정지
	void stimPack() { /* .*/} //스팀팩을 사용한다
}
class Tank { // 탱크
	int x, y; // 현재 위치
	void move(int x, int y) { /* */ } //지정된 위치로 이동
	void stop() { /* */ } //현재 위치에 정지
	void changeMode() { /* . */} //공격모드를 변환한다
}
class Dropship { // 수송선
	int x, y; // 현재 위치
	void move(int x, int y) { /* */ }// 지정된 위치로 이동
	void stop() { /* */ } //현재 위치에 정지
	void load() { /* .*/ } //선택된 대상을 태운다
	void unload() { /* .*/ } //선택된 대상을 내린다
}
public class JavaExercise7_17 {
		abstract class Unit {
		int x, y;
		abstract void move(int x, int y);
		void stop() { /* */ }	
	
	class Marine extends Unit{ // 보병
		void move(int x, int y) { }
		void stimPack() { /* .*/}
		}
		class Tank extends Unit{ // 탱크
		void move(int x, int y) { }
		void changeMode() { /* . */} 
		}
		class Dropship extends Unit{ // 수송선
		void move(int x, int y) { }
		void load() { /* .*/ } 
		void unload() { /* .*/ } 
		}
	}
}

 

 

 

7-18 다음과 같은 실행결과를 얻도록 코드를 완성하시오.

메서드명 : action

기     능 : 주어진 객체의 메서드를 호출한다.

              DanceRobot인 경우, dance()를 호출하고,

              SingleRobot인 경우, sing()를 호출하고,

              DrawRobot인 경우, draw()를 호출한다.

반환 타입 : 없음

매개변수 : Robot r - Robot인스턴스 또는 Robot의 자손 인스턴스

public class JavaExercise7_18 {
	public static void main(String[] args) {
		Robot[] arr = { new DanceRobot(), new SingRobot(), new DrawRobot() };
		for (int i = 0; i < arr.length; i++)
			action(arr[i]);
	} // main
}

class Robot {
}

class DanceRobot extends Robot {
	void dance() {
		System.out.println("춤을 춥니다");
	}
}

class SingRobot extends Robot {
	void sing() {
		System.out.println("노래를 합니다");
	}
}

class DrawRobot extends Robot {
	void draw() {
		System.out.println("그림을 그립니다");
	}
}
춤을 춥니다
노래를 합니다
그림을 그립니다

 

 

 

public class JavaExercise7_18 {
	public static void action(Robot r) {
		if (r instanceof DanceRobot) {
			DanceRobot dr = (DanceRobot) r;
			dr.dance();
		} else if (r instanceof SingRobot) {
			SingRobot sr = (SingRobot) r;
			sr.sing();
		} else if (r instanceof DrawRobot) {
			DrawRobot dr = (DrawRobot) r;
			dr.draw();

		}

	}

	public static void main(String[] args) {
		Robot[] arr = { new DanceRobot(), new SingRobot(), new DrawRobot() };
		for (int i = 0; i < arr.length; i++)
			action(arr[i]);
	} // main
}

class Robot {
}

class DanceRobot extends Robot {
	void dance() {
		System.out.println("춤을 춥니다");
	}
}

class SingRobot extends Robot {
	void sing() {
		System.out.println("노래를 합니다");
	}
}

class DrawRobot extends Robot {
	void draw() {
		System.out.println("그림을 그립니다");
	}
}
춤을 춥니다
노래를 합니다
그림을 그립니다

 

 

 

7-19 다음은 물건을 구입하는 사람을 정의한 BUyer클래스이다. 이 클래스는 멤버 변수로 돈(money)과 장 바위나(cart)를 가지고 있다. 제품을 구입하는 기능의 buy메서드와 장바구니에 구입한 물건을 추가하는 add메서드, 구입한 물건의 목록과 사용금액, 그리고 남은 금액을 출력하는 summary메서드를 완성하시오

 

1. 메서드명 : buy

   기      능 : 지정된 물건을 구입한다. 가진 돈(money)에서 물건의 가격을 빼고, 장바구니(cart)에 넣는다.

                 만일 가진 돈이 물건의 가격보다 적다면 바로 종료한다.

   반환 타입 : 없음

   매개변수 : Product p - 구입할 물건

 

2. 메서드명 : add

   기      능 : 지정된 물건을 장바구니에 담는다.

                 만일 지정된 장바구니에 담을 공간이 없으면, 장바구니의 크기를 2배로 늘린 다음에 담는다.

   반환타입 : 없음

   매개변수 : Product p - 구입한 물건

 

3. 메서드명 : summary

   기      능 : 구입한 물건의 목록과 사용금액, 남은 금액을 출력한다.

   반환타입 : 없음

   매개변수 : 없음

class Exercise7_19 {
	public static void main(String args[]) {
		Buyer b = new Buyer();
		b.buy(new Tv());
		b.buy(new Computer());
		b.buy(new Tv());
		b.buy(new Audio());
		b.buy(new Computer());
		b.buy(new Computer());
		b.buy(new Computer());
		b.summary();
	}
}

class Buyer {
	int money = 1000;
	Product[] cart = new Product[3]; // 구입한 제품을 저장하기 위한 배열
int i = 0; // Product cart index 배열 에 사용될

void buy(Product p) {
// 1.1 . 가진 돈과 물건의 가격을 비교해서 가진 돈이 적으면 메서드를 종료한다
if(money < p.price) {
System.out.println(" "+ p +" / ."); 잔액이 부족하여 을 를 살수 없습니다
return;
}
잔액이 부족하여 을 를 살수 없습니다 Computer / .
구입한 물건:Tv,Computer,Tv,Audio,Computer,Computer,
사용한 금액:850
남은 금액:150

 

 

 

class Exercise7_19 {
	public static void main(String args[]) {
		Buyer b = new Buyer();
		b.buy(new Tv());
		b.buy(new Computer());
		b.buy(new Tv());
		b.buy(new Audio());
		b.buy(new Computer());
		b.buy(new Computer());
		b.buy(new Computer());
		b.summary();
	}
}

class Buyer {
	int money = 1000;
	Product[] cart = new Product[3]; // 구입한 제품을 저장하기 위한 배열
	int i = 0; // Product cart index 배열 에 사용될

	void buy(Product p) {
		if (money < p.price)
			return;
		else if (true) {
			money -= p.price;
			add(p);
		}
		cart[i++] = p;
	}

	void add(Product p) {
		if (i >= cart.length) {
			Product[] tmp = new Product[cart.length * 2];
			System.arraycopy(cart, 0, tmp, 0, cart.length);
			cart = tmp;
		}
	}

	void summary() {
		String itemList = "";
		int sum = 0;
		for (int i = 0; i < cart.length; i++) {
			if (cart[i] == null)
				break;
			itemList += cart[i] + ",";
			sum += cart[i].price;
		}
		System.out.println(" :" + itemList);
		System.out.println(" :" + sum);
		System.out.println(" :" + money);
	} 
}

class Product {
	int price; // 제품의 가격

	Product(int price) {
		this.price = price;
	}
}

class Tv extends Product {
	Tv() {
		super(100);
	}

	public String toString() {
		return "Tv";
	}
}

class Computer extends Product {
	Computer() {
		super(200);
	}

	public String toString() {
		return "Computer";
	}
}

class Audio extends Product {
	Audio() {
		super(50);
	}

	public String toString() {
		return "Audio";
	}
}

 

 

 

 

 

7-20 다음의 코드를 실행한 결과를 적으시오.

class Exercise7_20 {
	public static void main(String[] args) {
		Parent p = new Child();
		Child c = new Child();
		System.out.println("p.x = " + p.x);
		p.method();
		System.out.println("c.x = " + c.x);
		c.method();
	}
}

class Parent {
	int x = 100;

	void method() {
		System.out.println("Parent Method");
	}
}

class Child extends Parent {
	int x = 200;

	void method() {
		System.out.println("Child Method");
	}
}
p.x = 100
Child Method
c.x = 200
Child Method

+ Recent posts