19일 차 - 정보 은닉, 접근 제한자(Access Modifier) (23.01.19)

yvonne·2023년 1월 19일
0

📂Java

목록 보기
19/51
post-thumbnail

1. 정보 은닉에 대하여 설명하시오.

  • 정보 은닉(Hidden Information): 클래스 내부에서 사용할 변수나 메소드를 private으로 선언해서 외부에서 접근하지 못하도록 하는 것
  • 방법: 데이터 멤버 변수는 private로 막고 데이터 멤버 변경은 함수를 통해서 진행한다.
class Rectangle {
	private int width, height; // 변수에 private 선언

	public Rectangle(int width, int height) {  	// 함수에 public 선언
		setWidth(width);
		setHeight(height);
	}




2. 접근 제한자 4가지에 대하여 설명하시오.

접근 제어자적용 범위
private같은 클래스 내부에서만 접근 가능
default (앞에 아무것도 없는 경우)같은 패키지 내부에서만 접근 가능
protected같은 패키지 내부와 상속 관계의 클래스에서만 접근할 수 있고 그 외 클래스에서는 접근 불가능
public외부 클래스 어디에서나 접근 가능




3. 아래의 프로그램을 작성 하시오.

  • 다음 멤버를 가지고 직사각형을 표현하는 Rectangle 클래스를 작성하라.
  • int 타입의 x, y, width, height 필드: 사각형을 구성하는 점과 크기 정보
  • x, y, width, height 값을 매개변수로 받아 필드를 초기화하는 생성자
  • int square() : 사각형 넓이 리턴
  • void show() : 사각형의 좌표와 넓이를 화면에 출력
  • boolean contatins(Rectangle r) : 매개변수로 받은 r이 현 사각형 안에 있으면 true 리턴
  • main() 메소드의 코드와 실행 결과는 다음과 같다

public static void main(String[] args) {
Rectangle r = new Rectangle(2, 2, 8, 7);
Rectangle s = new Rectangle(5, 5, 6, 6);
Rectangle t = new Rectangle(1, 1, 10, 10);
 
r.show();
System.out.println("s의 면적은 "+s.square());
if(t.contains(r)) System.out.println("t는 r을 포함합니다.");
if(t.contains(s)) System.out.println("t는 s를 포함합니다.");
}

  • 출력
    (2,2)에서 크기가 8x7인 사각형
    s의 면적은 36
    t는 r을 포함합니다.

package privatetest;

class Rectangle {
	private int x, y, width, height;

	public Rectangle(int x, int y, int width, int height) {
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
	}

	public void show() {
		System.out.println("(" + x + "," + y + ")에서 크기가 " + width + "x" + height + "인 사각형");
	}

	public boolean contains(Rectangle r) {
		return (this.x < r.x) && (r.x + r.width <= this.x + this.width) && (this.y < r.y)
				&& (r.y + r.height <= this.y + this.height);
	}
}

public class PrivateTest3 {

	public static void main(String[] args) {
		Rectangle r = new Rectangle(2, 2, 8, 7);
		Rectangle s = new Rectangle(5, 5, 6, 6);
		Rectangle t = new Rectangle(1, 1, 10, 10);

		r.show();
		System.out.println("s의 면적은 " + s.square());
		if (t.contains(r))
			System.out.println("t는 r을 포함합니다.");
		if (t.contains(s))
			System.out.println("t는 s를 포함합니다.");
	}
}
  • 출력결과
profile
개발 연습장

0개의 댓글