캡슐을 깨지 못하게 하는 도구 : 접근 제어 지시자

접근지시자 동일 클래스 파생 클래스 외부 클래스
private o x x
protected o o x
public o x o
import java.util.Scanner;

public class ExamList {
	private Exam[] exams;
	private int current;
	
	
	public void printList() {
		this.printList(this.current);
	}

	public void printList(int size) {
		System.out.println("┌──────────────────┐");
		System.out.println("│     성적 출력             │");
		System.out.println("└──────────────────┘");
		System.out.println();
			
		//int size = list.current;
		Exam[] exams = this.exams;
			
		for(int i= 0; i<size; i++ ) {
			Exam exam = exams[i];
			int kor = exam.kor;
			int eng = exam.eng;
			int math = exam.math;
				
			int total = kor+eng+math; 
			float avg= total/3.0f;
				
			System.out.printf("국어 :%d\n", kor);
			System.out.printf("영어 :%d\n", eng);
			System.out.printf("수학 :%d\n", math);
			
			System.out.printf("총점 : %3d\n", total);
			System.out.printf("평균 : %6.2f\n", avg);
			System.out.println("────────────────────────");
			}
	}
	
		
	public void inputList() {
			Scanner scan = new Scanner(System.in);
			System.out.println("┌──────────────────┐");
			System.out.println("│     성적 입력             │");
			System.out.println("└──────────────────┘");
			System.out.println();
			
				int kor, eng, math;
				
					do {
						System.out.printf("국어 :");
						kor = scan.nextInt();
						
						if(kor < 0 || 100 < kor)
						{
							System.out.println("국어성적은 0~100까지의 범위만 입력이 가능합니다.");
						}
					}while(kor<0 || 100 < kor);
					
					do {
						System.out.printf("영어 :");
						eng = scan.nextInt();
						
						if(eng < 0 || 100 < eng)
						{
							System.out.println("국어성적은 0~100까지의 범위만 입력이 가능합니다.");
						}
					}while(eng<0 || 100 < eng);
					
					do {
						System.out.printf("수학 :");
						math = scan.nextInt();
						
						if(math < 0 || 100 < math)
						{
							System.out.println("국어성적은 0~100까지의 범위만 입력이 가능합니다.");
						}
					}while(math<0 || 100 < math);
					Exam exam = new Exam();
					exam.kor=kor;
					exam.eng=eng;
					exam.math=math;
					
					Exam[] exams = this.exams;
					int size = this.current;
					
					if(exams.length == size) {
						//1. 크기가 5개 정도 더큰 새 배열을 생성하시오
						Exam [] temp = new Exam[exams.length +5];
						//2. 값을 이주시키기
						for(int i=0; i<size;i++)
							temp[i] = exams[i];
						//3. list.exams가 새로만든 temp 배열을 참조하도록 한다.
						this.exams = temp;
						
						
					}
					this.exams[this.current] = exam;   // 꼭해줘야하는 작업
					this.current++;
		
			
			System.out.println("────────────────────────");
	}


		public void init() {
			this.exams = new Exam[3];
			this.current=0; 
		} 

}

전예제 문제에서 수정했다. 데이터 구조에 관련된건 -> private 서비스에 관련된 것 -> public

캡슐이란 자기가 숨겨야할것에 대해서 은닉시킬수있는 능력이있어야한다. 은닉시킬수있도록 하기위한 도구가 private 이 있다.

참고 :https://youtu.be/WFViCDrPbw4

댓글남기기