7-1. 섯다 카드 20장을 포함하는 섯다 카드 한 벌(SutdaDeck)을 정의한 것이다. 섯다 카드 20장을 담는 StudaCard배열을 초기화하시오. 단, 섯다 카드는 1부터 10까지의 숫자가 적힌 카드가 한 쌍씩 있고, 숫자가 1, 3, 8인 경우에는 둘 중의 한 장은 광(Kwang)이어야 한다. 즉, SutdaCard의 인스턴스 변수 isKwang의 값이 true이어야 한다.
-----------------------------------------------------------------------------------------------------
class SutdaDeck{
final int CARC_NUM = 20;
public SutdaCard[] cards = new SutdaCard[CARC_NUM];
public SutdaDeck() {
for(int i=0;i<10;i++){
if(i == 0 || i == 2 || i == 7){
cards[i] = new SutdaCard(i+1,true);
cards[i+10] = new SutdaCard(i+1,false);
}else{
cards[i] = new SutdaCard(i+1,false);
cards[i+10] = new SutdaCard(i+1,false);
}
}
}
}
class SutdaCard {
int num;
boolean isKwang;
public SutdaCard() {
this(1,true);
}
SutdaCard(int num, boolean isKwang){
this.num = num;
this.isKwang = isKwang;
}
public String toString(){
return num+(isKwang?"K":"");
}
}
public class ch07 {
public static void main(String[] args) {
SutdaDeck deck = new SutdaDeck();
for(int i=0;i<deck.cards.length;i++)
System.out.print(deck.cards[i]+",");
}
}
-----------------------------------------------------------------------------------------------------
7-2. 문제 7-1의 SutdaDeck클래스에 다음에 정의된 새로운 메서드를 추가하고 테스트 하시오.
[주의] Math.random()을 사용하는 경우 실행결과와 다를 수 있음.
1.
메서드명 : shuffle
기능 : 배열 cards에 담긴 카드의 위치를 뒤섞는다.(Math.random() 사용)
반환타입 : 없음
매개변수 : 없음
2.
메서드명 : pick
기능 : 배열 cards에서 지정된 위치의 SutdaCard를 반환한다.
반환타입 : SutdaCard
매개변수 : int index - 위치
3.
메서드명: pick
기능 : 배열 cards에서 임의의 위치의 SutdaCard를 반환한다.(Math.random() 사용)
반환타입 : SutdaCard
매개변수 : 없음
-----------------------------------------------------------------------------------------------------
public void shuffle(){
for(int i=0;i<100;i++){
int index = (int)(Math.random()*19)+1;
SutdaCard tmp = cards[0];
cards[0] = cards[index];
cards[index] = tmp;
}
}
public SutdaCard pick(int index){
return cards[index];
}
public SutdaCard pick(){
return cards[(int)(Math.random()*20)+1];
}
-----------------------------------------------------------------------------------------------------
7-3. 오버라이딩의 정의와 필요성에 대해서 설명하시오.
- 조상 클래스로부터 상속받은 메서드의 내용을 변경하는 것을 오버라이딩이라고 한다. 상속받은 부모의 메서드를 각각의 자식 클래스에 맞추어 재정의하기위해 사용한다. 예를 들어 조상인 사람클래스로부터 손을 들다라는 메서드를 상속받았을 경우 왼손잡이는 왼손을 오른손잡이는 오른손을 들어야한다. 이와같이 메서드가 하는 일은 동일하지만 각 클래스에서의 구현부가 다를경우 오버라이딩한다. 또는 자식클래스의 멤버변수를 추가해야하거나 부모클래스에서 정의된 메서드만으로는 부족할때 오버라이딩하여 사용한다.
7-4. 다음 중 오버라이딩의 조건으로 옳지 않은 것은?(모두 고르시오) 없다 틀림
- 조상의 메서드와 이름이 같아야 한다.
- 매개변수의 수와 타입이 모두 같아야 한다.
- 리턴타입이 같아야 한다.
- 접근 제어자는 조상의 메서드보다 좁은 범위로만 변경할 수 있다.
- 조상의 메서드보다 더 많은 수의 예외를 선언할 수 없다.
- D,E는 조상클래스의 메서드를 자손클래스에서 오버라이딩 할 때의 조건이다.
7-5. 다음의 코드는 컴파일하면 에러가 발생한다. 그 이유를 설명하고 에러를 수정하기 위해서는 코드를 어떻게 바꾸어야 하는가?
-----------------------------------------------------------------------------------------------------
class Product{
int price;
int bonusPoint;
A. public Product(){}
public Product(int price) {
this.price = price;
bonusPoint = (int)(price/10.0);
}
}
class Tv extends Product{
Tv(){ B. super(int형 value); } // Implicit super constructor Product() is undefined.
public String toString(){
return "Tv";
}
}
public class ch07 {
public static void main(String[] args) {
Tv t = new Tv();
}
}
-----------------------------------------------------------------------------------------------------
- Product를 상속하고 있으므로 Tv객체를 생성하면 부모의 생성자를 호출하게되는데 사용자가 아무런 호출도 안해주고 있으므로 컴파일러가 부모의 기본 생성자를 호출한다.(super();) 그러나 Product클래스에 사용자가 선언한 임의의 생성자만 있고 기본생성자가 없으므로 에러가 난다. 사용자가 선언한 임의의 생성자가 있을 경우 컴파일러는 기본생성자를 자동으로 추가하지 않는다. 따라서 Product클래스에 기본 생성자를 추가하면 된다. => 답 A
혹은 기본생성자 대신 사용자가 임의로 선언한 생성자를 호출하여도 에러가 나지 않는다. => 답 B
7-6. 자손 클래스의 생성자에서 조상 클래스의 생성자를 호출해야하는 이유는 무엇인가?
- 자손 클래스는 조상 클래스의 확장한 형태이다. 즉, 조상 클래스의 멤버변수와 멤버 메서드를 포함하고 있다. 또한 자손 클래스에서 조상 클래스의 멤버변수와 멤버메서드에 접근할 수 있으며 조작할 수 있다. 따라서 자손 클래스가 준비되기 전에 조상 클래스를 준비해주어야한다. 그렇기 때문에 자손 클래스의 생성자의 맨 첫줄에서(자손 클래스 초기화전에 제일 먼저) 조상 클래스의 생성자를 호출하는 것이다.
7-7. 다음 코드의 실행했을 때 호출되는 생성자의 순서와 실행결과를 적으시오.
-----------------------------------------------------------------------------------------------------
class Parent{
int x = 100;
Parent(){
this(200);
}
Parent(int x){
this.x = x;
}
int getX(){
return x;
}
}
class Child extends Parent{
int x = 3000;
Child(){
this(1000);
}
Child(int x){
this.x = x;
}
}
public class ch07 {
public static void main(String[] args) {
Child c = new Child();
System.out.println("x="+c.getX());
}
}
-----------------------------------------------------------------------------------------------------
- Child() -> Parent() -> Parent(int) -> this(@) -> Child(int)
- 실행결과 : x = 200
7-8. 다음 중 접근제어자를 접근범위가 넓은 것에서 좁은 것의 순으로 바르게 나열한 것은?
- public - protected - (default) - private
- public - (default) - protected - private
- (default) - public - protected - private
- private - protected - (default) - public
7-9. 다음 중 제어자 final을 붙일 수 있는 대상과 붙였을 때 그 의미를 적은 것이다. 옳지 않은 것은? (모두 고르시오)
- 지역변수 - 값을 변경할 수 없다.
- 클래스 - 상속을 통해 클래스에 새로운 멤버를 추가할 수 없다.
- 메서드 - 오버로딩을 할 수 없다.
- 멤버변수 - 값을 변경할 수 없다.
7-10. MyTv2클래스의 멤버변수 isPowerOn, channel, volume을 클래스 외부에서 접근할 수 없도록 제어자를 붙이고 대신 이 멤버변수들의 값을 어디서나 읽고 변경할 수 있도록 getter와 setter메서드를 추가하라.
-----------------------------------------------------------------------------------------------------
class MyTv2{
private boolean isPowerOn;
private int channel;
private int volume;
final int MAX_VOLUME = 100;
final int MIN_VOLUME = 0;
final int MAX_CHANNEL = 100;
final int MIN_CHANNEL = 1;
public boolean isPowerOn() {
return isPowerOn;
}
public void setPowerOn(boolean isPowerOn) {
this.isPowerOn = isPowerOn;
}
public int getChannel() {
return channel;
}
public void setChannel(int channel) {
this.channel = channel;
}
public int getVolume() {
return volume;
}
public void setVolume(int volume) {
this.volume = volume;
}
}
public class ch07 {
public static void main(String[] args) {
MyTv2 t = new MyTv2();
t.setChannel(10);
System.out.println("CH:"+t.getChannel());
t.setVolume(20);
System.out.println("VOL:"+t.getVolume());
}
}
-----------------------------------------------------------------------------------------------------
7-11. 문제7-10에서 작성한 MyTv2클래스에 이전 채널(previous channel)로 이동하는 기능의 메서드를 추가해서 실행결과와 같은 결과를 얻도록 하시오.
[힌트] 이전 채널의 값을 저장할 멤버변수를 정의하라.
메서드명 : gotoPrevChannel
기능 : 현재 채널을 이전 채널로 변경한다.
반환타입 : 없음
매개변수 : 없음
-----------------------------------------------------------------------------------------------------
class MyTv2{
private boolean isPowerOn;
private int channel;
private int volume;
private int[] prevChannel = new int[100];
private int index = 0;
private int pointer = 0;
final int MAX_VOLUME = 100;
final int MIN_VOLUME = 0;
final int MAX_CHANNEL = 100;
final int MIN_CHANNEL = 1;
public boolean isPowerOn() {
return isPowerOn;
}
public void setPowerOn(boolean isPowerOn) {
this.isPowerOn = isPowerOn;
}
public int getChannel() {
return channel;
}
public void setChannel(int channel) {
this.channel = channel;
prevChannel[index] = channel;
index++;
}
public int getVolume() {
return volume;
}
public void setVolume(int volume) {
this.volume = volume;
}
public void gotoPrevChannel(){
setChannel(prevChannel[pointer]);
pointer++;
}
}
public class ch07 {
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. 다음 중 접근 제어자에 대한 설명으로 옳지 않은 것은? (모두 고르시오)
- public은 접근제한이 전혀 업는 접근 제어자이다.
- (default)가 붙으면, 같은 패키지 내에서만 접근이 가능하다.
- 지역변수에도 접근 제어자를 사용할 수 있다.
- protected가 붙으면, 같은 패키지 내에서도 접근이 가능하다.
- protected가 붙으면, 다른 패키지의 자손 클래스에서 접근이 가능하다.
7-13. Math클래스의 생성자는 접근 제어자가 private이다. 그 이유는 무엇인가?
- Math클래스의 모든 메서드가 static메서드이고 인스턴스 변수가 존재하지 않기 때문에 객체를 생성할 필요가 없기 때문이다.
7-14. 문제 7-1에 나오는 섯다카드의 숫자와 종류(isKwang)는 사실 한번 값이 지정되면 변경되어서는 안 되는 값이다. 카드의 숫자가 한번 잘못 바뀌면 똑같은 카드가 두 장이 될 수 도 있기 때문이다. 이러한 문제점이 발생하지 않도록 아래의 SutdaCard를 수정하시오.
-----------------------------------------------------------------------------------------------------
class SutdaCard {
final int num;
final boolean isKwang;
public SutdaCard() {
this(1,true);
}
SutdaCard(int num, boolean isKwang){
this.num = num;
this.isKwang = isKwang;
}
public String toString(){
return num+(isKwang?"K":"");
}
}
-----------------------------------------------------------------------------------------------------
7-15. 클래스가 다음과 같이 정의되어 있을 때, 형변환을 올바르게 하지 않은 것은? (모두 고르시오.) 없다. 틀림
-----------------------------------------------------------------------------------------------------
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();
----------------------------------------------------------------------------------------------------
- u = (Unit)ac;
- u = ac;
- GroundUnit gu = (GroundUnit)u;
- AirUnit au = ac;
- t = (Tank)u;
- GroundUnit gu2 = t;
- 조상타입의 인스턴스를 자손타입으로 형변환 할 수 없다.
7-16. 다음 중 연산결과가 true가 아닌 것은? (모두 고르시오)
----------------------------------------------------------------------------------------------------
class Car{}
class FireEngine extends Car implements Movable{}
class Ambulance extends Car{}
FireEngine fe = new FireEngine();
----------------------------------------------------------------------------------------------------
- fe instanceof FireEngine
- fe instanceof Movable
- fe instanceof Object
- fe instanceof Car
- fe instanceof Ambulance
7-17. 아래 세 개의 클래스로부터 공통부분을 뽑아서 Unit이라는 클래스를 만들고, 이 클래스를 상속받도록 코드를 변경하시오.
----------------------------------------------------------------------------------------------------
class Unit{
int x, y;
void move(int x, int y){}
void stop(){}
}
class Marine extends Unit{
void stimPack(){}
}
class Tank extends Unit{
void changeMode(){}
}
class Dropship extends Unit{
void unload(){}
}
----------------------------------------------------------------------------------------------------
7-18. 다음과 같은 실행결과를 얻도록 코드를 완성하시오.
[Hint] instanceof 연산자를 사용해서 형변환한다.
메서드명 : action
기능 : 주어진 객체의 메서드를 호출한다. DanceRobot()인 경우, dance()를 호출하고, SingRobot인 경우, sing()을 호출하고, DrawRobot()인 경우, draw()를 호출한다.
반환타입 : 없음
매개변수 : Robot r - Robot 인스턴스 또는 Robot의 자손 인스턴스
----------------------------------------------------------------------------------------------------
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 ch07 {
static void action(Robot r){
if(r instanceof DanceRobot)
((DanceRobot) r).dance();
if(r instanceof SingRobot)
((SingRobot) r).sing();
if(r instanceof DrawRobot)
((DrawRobot) r).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]);
}
}
----------------------------------------------------------------------------------------------------
7-19. 다음은 물건을 구입하는 사람을 정의한 Buyer클래스이다. 이 클래스는 멤버변수로 돈과 장바구니를 가지고 있다. 제품을 구입하는 기능의 buy메서드와 장바구니에 구입한 물건을 추가하는 add메서드, 구입한 물건의 목록과 사용금액, 그리고 남은 금액을 출력하는 summary메서드를 완성하시오.
1.
메서드명 : buy
기능 : 지정된 물건을 구입한다. 가진 돈에서 물건의 가격을 빼고, 장바구니에 담는다. 만일 가진돈이 물건의 가격보다 적다면 바로 종료한다.
반환타입 : 없음
매개변수 : Product p - 구입할 물건
2.
메서드명 : add
기능 : 지정된 물건을 장바구니에 담는다. 만일 장바구니에 담을 공간이 없으면, 장바구니의 크기를 2배로 늘린 다음에 담는다.
반환타입 : 없음
매개변수 : Product p - 구입할 물건
3.
메서드명 : summary
기능 : 구입한 물건으리 목록과 사용금액, 남은 금액을 출력한다.
반환타입 : 없음
매개변수 : 없음
----------------------------------------------------------------------------------------------------
class Buyer{
int money = 1000;
Product2[] cart = new Product2[3];
int i = 0;
void buy(Product2 p){
if(money < p.price){
System.out.println("잔액이 부족하여"+p+"을/를 살수 없습니다.");
return;
}
money -= p.price;
add(p);
}
void add(Product2 p){
if(i >= cart.length){
Product2[] cart2 = new Product2[cart.length*2];
for(int j=0;j<cart.length;j++)
cart2[j] = cart[j];
cart = cart2;
}
cart[i] = p;
i++;
}
void summary(){
String result = "";
int total = 0;
for(int j=0;j<cart.length;j++){
result += cart[j];
total += cart[j].price;
}
System.out.println("구입한 물건 : "+result);
System.out.println("사용한 금액 : "+total);
System.out.println("남은 금액 : "+money);
}
}
class Product2{
int price;
Product2(int price){
this.price = price;
}
}
class Tv2 extends Product2{
Tv2() { super(100); }
public String toString() { return "Tv"; }
}
class Computer2 extends Product2{
Computer2() { super(200); }
public String toString() { return "Computer"; }
}
class Audio2 extends Product2{
Audio2() { super(50); }
public String toString() { return "Audio"; }
}
public class ch07 {
public static void main(String[] args) {
Buyer b = new Buyer();
b.buy(new Tv2());
b.buy(new Computer2());
b.buy(new Tv2());
b.buy(new Audio2());
b.buy(new Computer2());
b.buy(new Computer2());
b.buy(new Computer2());
b.summary();
}
}
----------------------------------------------------------------------------------------------------
7-20. 다음의 코드를 실행한 결과를 적으시오.
----------------------------------------------------------------------------------------------------
class Parent2{
int x = 100;
void method(){
System.out.println("Parent Method");
}
}
class Child2 extends Parent2{
int x = 200;
void method(){
System.out.println("Child Method");
}
}
public class ch07 {
public static void main(String[] args) {
Parent2 p = new Child2();
Child2 c = new Child2();
System.out.println("p.x = "+p.x);
p.method();
System.out.println("p.x = "+c.x);
c.method();
}
}
----------------------------------------------------------------------------------------------------
- p.x = 100
Child Method
p.x = 200
Child Method
7-21. 다음과 같이 attack메서드가 정의되어 있을 때, 이 메서드의 매개변수로 가능한것 두 가지를 적으시오.
----------------------------------------------------------------------------------------------------
interface Movable{
void move(int x, int y);
}
void attack(Movable f){}
----------------------------------------------------------------------------------------------------
- Movable을 구현한 객체, Movable을 구현한 객체를 상속받은 객체
7-22. 아래는 도형을 정의한 Shape클래스이다. 이 클래스를 조상으로 하는 Circle클래스와 Rectangle클래스를 작성하시오. 이 때, 생성자도 각 클래스에 맞게 적절히 추가해야한다.
1.
클래스명 : Circle
조상클래스 : Shape
멤버변수 : double r - 반지름
2.
클래스명 : Rectangle
조상클래스 : Shape
멤버변수 : double width - 폭, double height - 높이
3.
메서드명 : isSquare
기능 : 정사각형인지 아닌지를 알려준다.
반환타입 : boolean
매개변수 : 없음
----------------------------------------------------------------------------------------------------
abstract class Shape{
Point p;
Shape(){
this(new Point(0,0));
}
Shape(Point p){
this.p = p;
}
abstract double calcArea();
public Point getP() {
return p;
}
public void setP(Point p) {
this.p = p;
}
}
class Point{
int x, y;
Point(){
this(0,0);
}
Point(int x, int y){
this.x = x;
this.y = y;
}
public String toString(){
return "["+x+","+y+"]";
}
}
class Circle extends Shape{
double r;
final double PI = 3.14;
Circle(double r){
this.r = r;
}
public double calcArea(){
return PI*(r*r);
}
}
class Rectangle extends Shape{
double width;
double height;
Rectangle(double width, double height){
this.width = width;
this.height = height;
}
public double calcArea(){
return width*height;
}
public boolean isSquare(){
boolean result = false;
if(width == height)
result = true;
return result;
}
}
----------------------------------------------------------------------------------------------------
7-23. 문제7-22에서 정의한 클래스들의 면적을 구하는 메서드를 작성하고 테스트 하시오.
1.
메서드명 : sumArea
기능 : 주어진 배열에 담긴 도형들의 넓이를 모두 더해서 반환한다.
반환타입 : double
매개변수 : Shape[] arr
----------------------------------------------------------------------------------------------------
public class ch07 {
static double sumArea(Shape[] arr){
double result = 0.0;
for(int i=0;i<arr.length;i++)
result += arr[i].calcArea();
return result;
}
public static void main(String[] args) {
Shape[] arr = {new Circle(5.0), new Rectangle(3, 4), new Circle(1.0)};
System.out.println("면적의 합 : "+sumArea(arr));
}
}
----------------------------------------------------------------------------------------------------
7-24. 다음 중 인터페이스의 장점이 아닌 것은?
- 표준화를 가능하게 해준다.
- 서로 관계없는 클래스들에게 관계를 맺어 줄 수 있다.
- 독립적인 프로그램이이 가능하다.
- 다중상속을 가능하게 해준다.
- 패키지간의 연결을 도와준다.
'예전 포스팅 모음' 카테고리의 다른 글
[DB] select 예제, golden tool 사용법, 문자열 연산자, drop, sqlldr(sqlloader)의 사용 (0) | 2014.09.22 |
---|---|
[java] 자바의 정석 연습문제 ch08 (0) | 2014.09.19 |
[java] 자바의 정석 연습문제 ch05 (0) | 2014.09.19 |
[java] 자바의 정석 연습문제 ch04 (0) | 2014.09.19 |
[java] 자바의 정석 연습문제 ch03 (0) | 2014.09.19 |