쌓고 쌓다

[JAVA] 명품 자바 프로그래밍 5장 이론문제 본문

프로그래밍/java

[JAVA] 명품 자바 프로그래밍 5장 이론문제

승민아 2022. 6. 18. 16:53

1.

(1)

a, set()

(2)

a, b, c, set()

(3)

a, b, c, d, e, set()

(4)

1번 라인 -> private인 a는 수정 불가

 

2.

1번 Object 클래스

 

3.

class Pen
{
	private int amount;
	public int getAmount()
	{
		return amount;
	}
	public void setAmount(int amount)
	{
		this.amount=amount;
	}
}

class SharpPencil extends Pen
{
	private int width;
}

class BallPen extends Pen
{
	private String color;
	public String getColor()
	{
		return color;
	}
	public void setColor(String color)
	{
		this.color=color;
	}
}

class FountainPen extends BallPen
{
	public void refill(int n)
	{
		setAmount(n);
	}
}

 

4.

서브 클래스, extends, super, instanceof, implements

 

5.

2번 -> 다른 패키지에서 상속 받은 서브 클래스도 가능

 

6.

extends, super(size);

 

7. 

A

B:11

 

8.

A의 기본 생성자가 없다.

public A()
{
	a=i;
}

기본 생성자를 추가해주자.

 

9.

1번 -> 추상 메소드가 아닌 메소드는 구현되어 있어야한다.

3번 -> 추상 클래스를 상속 받고 구현하지 않으면 그 클래스도 추상 클래스여야 한다.

4번 -> 추상 클래스 B의 메소드 f()의 반환형이 int인데 상속 받아 오버라이딩할때 반환형이 이상하다. 반환형을 바꾸고 return 0;도 추가해주자.

 

10.

아래의 메소드를 B에 추가하자.

public boolean isOdd()
{
	if(n%2==0)
    	return true;
    else
    	return false;
}

 

11.

(1)

2번, 3번

 

(2)

true

false

 

(3)

true

true

 

12.

(1)

Circle

 

(2)

draw();

 

(3)

super.draw();

 

13.

(1)

2번, 4번 -> 추상 클래스는 객체 생성이 불가

( 구현이 다 되어있고 추상 클래스라도 생성이 안되더라. )

 

(2)

class Circle extends Shape{
	private int radius;
    public Circle(int radius) { this.radius = radius; }
    double getArea() { return 3.14*radius*radius; }
    
    public void draw()
    {
		System.out.println("반지름="+radius);
    }
}

 

14.

4번

 

15.

2번 -> 인터페이스에서 필드(멤버 변수)를 만들 수 없음. 상수 필드밖에 안됨 ( public static final int a = 5 )

또는 public static final 생략 가능하기에 int a = 5; 도 가능)

 

16.

interface, implements

interface Device{
	void on();
	void off();
}

public class Test implements Device{
	
	public void on()
	{
		System.out.println("켜졌습니다.");
	}
	
	public void off()
	{
		System.out.println("종료합니다.");
	}
	
	public void watch()
	{
		System.out.println("방송중입니다.");
	}
	
	public static void main(String[] args) {
		
		Test myTest = new Test();
		myTest.on();
		myTest.watch();
		myTest.off();
		
	}
}

 

인터페이스에 메소드

void on(); 은 사실 public abstract void on(); 으로 public abstract가 생략되었기에

인터페이스 device를 implements하여 구현할때 접근 지정자를 생략하면 디폴트이므로

원래 public인데 디폴트로 접근 범위가 줄어드니 이것은 에러가 난다.

그래서 인터페이스를 받아와 구현할때 생략되어있다고해서 우리도 생략하면 안된다.

public을 붙여주자.

 

 

Comments