티스토리 뷰

접근 지시제어자(private, protected, default, public) 를 배우고 데이터 보안(정보은닉)에 대해 알게 되었으니,


캡슐화에 대한 공부를 안할 수 가 없습니다.


캡슐화는 객체지향 기반의 클래스 설계에서 가장 기본이면서도 가장 중요한 원칙들 입니다.


가장 기본적인 실습 예제를 보면서 공부하도록 하겠습니다.



캡슐화 예제를 보여주는 계산기 클래스

public class Calculator {
  // 인스턴스 변수가 보이지 않게 정보를 은닉
	private int num1;
	private int num2;
	private int result;

	public void setNum1(int num1) {
		this.num1 = num1;
	}

	public void setNum2(int num2) {
		this.num2 = num2;
	}

	public int getResult() {
		return this.result;
	}

	// 사용자가 알 필요는 없지만 반드시 실행 해야 할 메소드
	private void specialAlgorithm() {
		System.out.println("특수 알고리즘 실행~~~~");
	}

	// 캡슐화의 예제
	public void runAdd() {
		specialAlgorithm();
		result = num1 + num2;
	}
}


계산기 클래스를 사용하는 메인 클래스

public class ExampleEncapsulation{
	public static void main(String[] args) {
		Calculator calc = new Calculator();
		calc.setNum1(10); // 사용자가 첫 번째 숫자 입력
		calc.setNum2(20); // 사용자가 두 번째 숫자 입력

		// 특수 알고리즘 실행
		// calc.specialAlgorithm();
		calc.runAdd();

		int addResult = calc.getResult();
		System.out.println("덧셈 결과 : " + addResult);

	}
}



캡슐화는 일관되게 적용할 수 있는 단순한 개념이 아니고, 


구현하는 프로그램의 성격과 특성에 따라서 적용하는 범위가 달라진다.


즉, 정답이라는 것이 딱히 없는 개념이다.


실습을 통해 공부하겠습니다.



원 넓이를 구하는 메소드를 캡슐화

public class Circle {
	private double r;
	private double area;
	private static final double PI = 3.14;

	public void setR(double r) {
		this.r = r;
	}

	public void showInfo() {
		makeArea();
		System.out.println("원 반지름 : " + this.r);
		System.out.println("원 넓이 : " + this.area);
	}

	private void makeArea() {
		this.area = this.r * this.r * PI;
	}
}



사각형 넓이를 구하는 메소드를 캡슐화

public class Square {
	private int heigth;
	private int width;
	private int area;

	public void setHeigth(int heigth) {
		this.heigth = heigth;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public void showInfo() {
		makeArea();
		System.out.println("사각형 가로길이 : " + this.width);
		System.out.println("사각형 세로길이 : " + this.heigth);
		System.out.println("사각형 넓이길이 : " + this.area);
	}

	private void makeArea() {
		area = width * heigth;
	}
}


캡슐화된 클래스 사용하는 메인 클래스

public class ExampleEncapsulation2{
	public static void main(String[] args) {
		Square square = new Square();
		Circle circle = new Circle();

		square.setWidth(10);
		square.setHeigth(20);

		square.showInfo();

		circle.setR(10);
		circle.showInfo();
	}
}

반응형
LIST
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
글 보관함