🧑‍💻복습/자바

자바 3주차 정리. 2부 패키지 분류. private와 getter setter

우동한그릇 2023. 6. 10. 13:35
반응형
#12. 클래스를 유지보수하기 쉽게 별도 소스 파일로 분리:
Score 클래스를 별도의 소스 파일로 분리. App 클래스와 Score 클래스가 서로 다른 파일에 위치.


#13. 클래스를 유지보수하기 쉽게 패키지로 분류:
Score 클래스를 bitcamp.test.step14.vo 패키지로 분류. 패키지를 도입하여 클래스를 논리적으로 그룹화


#14. 외부 접근 차단과 값 꺼내기:
Score 클래스의 sum과 aver 필드를 private으로 접근 제한자를 변경. 필드에 직접 접근할 수 없게 됩니다.
값을 꺼내기 위해 getter 메서드를 정의.


#15. 프로그래밍의 일관성을 위해 다른 필드에 대해서도 getter를 만들고 사용:
Score 클래스의 name 필드에 대해서도 getter를 정의.
일관성을 유지하기 위해 모든 필드에 대해 getter를 만들고 사용.


#16. 필드의 직접 접근을 막고 setter를 정의하는 이유:
Score 클래스의 필드에 대해 setter를 정의하여 값을 변경할 때 유효성을 검사.
무효한 값을 저장하는 것을 방지하기 위해 setter를 사용.


#17. 필드의 직접 접근을 막고 인스턴스 변수에 무효한 값이 저장되지 않게 하기 위해:
Score 클래스의 kor, eng, math 필드에 대해 private 접근 제한자를 적용.
값을 설정하는 setter 메서드를 통해 유효성을 검사하고 저장.

 

// 12) 클래스를 유지보수 하기 쉽게 별도 소스 파일로 분리

app.java

// 12) 클래스를 유지보수 하기 쉽게 별도 소스 파일로 분리
public class App {
  
  public static void main(String[] args) {

    final int MAX_SIZE = 10;
    Score[] scores = new Score[MAX_SIZE];
    int length = 0;

    scores[length++] = new Score("홍길동", 100, 100, 100);
    scores[length++] = new Score("임꺽정", 90, 90, 90);
    scores[length++] = new Score("유관순", 80, 80, 80);

    for (int i = 0; i < length; i++) {
      printScore(scores[i]);
    }

  }

  static void printScore(Score s) {
    System.out.printf("%s: 합계=%d, 평균=%.1f\n", 
      s.name, s.sum, s.aver);
  }

}

socre.java 

package bitcamp.test.step12;

class Score {
  String name;
  int kor;
  int eng;
  int math;
  int sum;
  float aver;

  Score(String name, int kor, int eng, int math) {
    this.name = name;
    this.kor = kor;
    this.eng = eng;
    this.math = math;
    this.compute();
  }

  void compute() {
    this.sum = this.kor + this.eng + this.math;
    this.aver = this.sum / 3f;
  }
}

// 13) 클래스를 유지보수 하기 쉽게 패키지로 분류: import, public

app.java

// 13) 클래스를 유지보수 하기 쉽게 패키지로 분류: import, public
public class App {
  
  public static void main(String[] args) {

    final int MAX_SIZE = 10;
    Score[] scores = new Score[MAX_SIZE];
    int length = 0;

    scores[length++] = new Score("홍길동", 100, 100, 100);
    scores[length++] = new Score("임꺽정", 90, 90, 90);
    scores[length++] = new Score("유관순", 80, 80, 80);

    for (int i = 0; i < length; i++) {
      printScore(scores[i]);
    }

  }

  static void printScore(Score s) {
    System.out.printf("%s: 합계=%d, 평균=%.1f\n", 
      s.name, s.sum, s.aver);
  }

}

score.java

package bitcamp.test.step14.vo;

public class Score {
  public String name;
  int kor;
  int eng;
  int math;
  public int sum;
  public float aver;

  public Score(String name, int kor, int eng, int math) {
    this.name = name;
    this.kor = kor;
    this.eng = eng;
    this.math = math;
    this.compute();
  }

  void compute() {
    this.sum = this.kor + this.eng + this.math;
    this.aver = this.sum / 3f;
  }
}

// 14) 외부접근 차단과 값 꺼내기 : private, getter

// 14) 외부접근 차단과 값 꺼내기 : private, getter
public class App {
  
  public static void main(String[] args) {

    final int MAX_SIZE = 10;
    Score[] scores = new Score[MAX_SIZE];
    int length = 0;

    scores[length++] = new Score("홍길동", 100, 100, 100);
    scores[length++] = new Score("임꺽정", 90, 90, 90);
    scores[length++] = new Score("유관순", 80, 80, 80);

    // 변수에 직접 접근 => 국영수 합계를 임의로 조작 가능 !
    scores[0].sum = 20000;

    for (int i = 0; i < length; i++) {
      printScore(scores[i]);
    }

  }

  static void printScore(Score s) {
    System.out.printf("%s: 합계=%d, 평균=%.1f\n", 
      s.name, s.getSum(), s.getAver());
  }

}

score.java

package bitcamp.test.step14.vo;

public class Score {
  public String name;
  int kor;
  int eng;
  int math;
  private int sum;
  private float aver;

  public Score(String name, int kor, int eng, int math) {
    this.name = name;
    this.kor = kor;
    this.eng = eng;
    this.math = math;
    this.compute();
  }

  void compute() {
    this.sum = this.kor + this.eng + this.math;
    this.aver = this.sum / 3f;
  }
  
  // getter : private 으로 접근이 막힌 변수의 값을 리턴해주는 메서드
  public int getSum() {
    return this.sum;
  }
  // getter : private 으로 접근이 막힌 변수의 값을 리턴해주는 메서드
  public float getAver() {
    return this.aver;
  }

}

// 15) 프로그래밍의 일관성을 위해 보통 다른 필드에 대해서도 getter를 만들고 사용한다.

// 15) 프로그래밍의 일관성을 위해 보통 다른 필드에 대해서도 getter를 만들고 사용한다.
public class App {
  
  public static void main(String[] args) {

    final int MAX_SIZE = 10;
    Score[] scores = new Score[MAX_SIZE];
    int length = 0;

    scores[length++] = new Score("홍길동", 100, 100, 100);
    scores[length++] = new Score("임꺽정", 90, 90, 90);
    scores[length++] = new Score("유관순", 80, 80, 80);

    // 변수에 직접 접근 => 국영수 합계를 임의로 조작 가능 !

    for (int i = 0; i < length; i++) {
      printScore(scores[i]);
    }

  }

  static void printScore(Score s) {
    System.out.printf("%s: 합계=%d, 평균=%.1f\n", 
      s.getName(), s.getSum(), s.getAver());
  }

}

score.java

package bitcamp.test.step15.vo;

public class Score {
  //일관성을 위해 private 처리
  private String name; 
  int kor;
  int eng;
  int math;
  private int sum;
  private float aver;

  public Score(String name, int kor, int eng, int math) {
    this.name = name;
    this.kor = kor;
    this.eng = eng;
    this.math = math;
    this.compute();
  }

  void compute() {
    this.sum = this.kor + this.eng + this.math;
    this.aver = this.sum / 3f;
  }
  
  // getter : private 으로 접근이 막힌 변수의 값을 리턴해주는 메서드
  public int getSum() {
    return this.sum;
  }
  // getter : private 으로 접근이 막힌 변수의 값을 리턴해주는 메서드
  public float getAver() {
    return this.aver;
  }

  public String getName() {
    return this.name;
  }

}

// 16) 필드의 직접 접근을 막고 setter를 정의하는 이유

// 16) 필드의 직접 접근을 막고 setter를 정의하는 이유
public class App {
  
  public static void main(String[] args) {

    final int MAX_SIZE = 10;
    Score[] scores = new Score[MAX_SIZE];
    int length = 0;

    scores[length++] = new Score("홍길동", 100, 100, 100);
    scores[length++] = new Score("임꺽정", 90, 90, 90);
    scores[length++] = new Score("유관순", 80, 80, 80);

    // 합계와 평균 계산이 끝난 후에 국어 점수를 변경한다면
    // => 국영수 점수와 합계, 평균 점수가 일치하지 않는 문제가 발생한다.
    // 데이터의 결함이 발생한다.
    // 국영수 점수를 변경한 후에 compute() 를 호출하면 되지 않을까 ?
    // 만약 개발자가 compute() 호출하는 것을 잊어버린다면 아무 소용이 없다.,
    // 만약 유효하지 않은 국영수 점수를 입력한다면? 이건 막을 방법이 없다.
    scores[0].kor = 7000; // 이렇게 무효한 점수를 입력하는 것을 막을 수 없다.
    // scores[0].compute(); //호출하지 않으면 아무 소용이 없다

    for (int i = 0; i < length; i++) {
      printScore(scores[i]);
    }

  }

  static void printScore(Score s) {
    System.out.printf("%s: 국어=%d, 영어=%d, 수학=%d, 합계=%d, 평균=%.1f\n", 
      s.getName(), s.kor, s.eng, s.math, s.getSum(), s.getAver());
  }

}

score.java

package bitcamp.test.step16.vo;

public class Score {
  //일관성을 위해 private 처리
  private String name; 
  public int kor;
  public int eng;
  public int math;
  private int sum;
  private float aver;

  public Score(String name, int kor, int eng, int math) {
    this.name = name;
    this.kor = kor;
    this.eng = eng;
    this.math = math;
    this.compute();
  }

  public void compute() {
    this.sum = this.kor + this.eng + this.math;
    this.aver = this.sum / 3f;
  }
  
  // getter : private 으로 접근이 막힌 변수의 값을 리턴해주는 메서드
  public int getSum() {
    return this.sum;
  }
  // getter : private 으로 접근이 막힌 변수의 값을 리턴해주는 메서드
  public float getAver() {
    return this.aver;
  }

  public String getName() {
    return this.name;
  }

}

// 17) 필드의 직접 접근을 막고 인스턴스 변수에 무효한 값이 저장되지 않게 하기 위해
//      => getter 정의하기 : 값을 꺼낼 때 사용
//      => setter 정의하기 : 값을 변경할 때 사용. 단 유효한 값을 저장하도록 통제한다.

// 17) 필드의 직접 접근을 막고 인스턴스 변수에 무효한 값이 저장되지 않게 하기 위해
//      => getter 정의하기 : 값을 꺼낼 때 사용
//      => setter 정의하기 : 값을 변경할 때 사용. 단 유효한 값을 저장하도록 통제한다.
public class App {
  
  public static void main(String[] args) {

    final int MAX_SIZE = 10;
    Score[] scores = new Score[MAX_SIZE];
    int length = 0;

    scores[length++] = new Score("홍길동", 100, 100, 100);
    scores[length++] = new Score("임꺽정", 90, 90, 90);
    scores[length++] = new Score("유관순", 80, 80, 80);


    // scores[0].kor = 7000; // 접근 불가 !
    scores[0].setKor(70); // setter 를 통해서는 값 변경가능. 단 유효값만 가능
    // scores[0].compute(); // 호출하는 것을 잊어버릴 수 있기 때문에 setter에서 호출
    
    for (int i = 0; i < length; i++) {
      printScore(scores[i]);
    }

  }

  static void printScore(Score s) {
    System.out.printf("%s: 국어=%d, 영어=%d, 수학=%d, 합계=%d, 평균=%.1f\n", 
      s.getName(), s.getKor(), s.getEng(), s.getMath(), s.getSum(), s.getAver());
  }

}

score.java

package bitcamp.test.step17.vo;

public class Score {
  //일관성을 위해 private 처리
  private String name; 

  // 직접 접근을 허용했을 때, 무효한 값을 저장할 수 있기 때문에
  // private 으로 접근을 막았다.
  private int kor;
  private int eng;
  private int math;
  private int sum;
  private float aver;

  public Score(String name, int kor, int eng, int math) {
    this.name = name;
    this.setKor(kor);
    this.setEng(eng);
    this.setMath(math);
    this.compute();
  }

  public void compute() {
    this.sum = this.kor + this.eng + this.math;
    this.aver = this.sum / 3f;
  }
  
  // getter : private 으로 접근이 막힌 변수의 값을 리턴해주는 메서드
  public int getSum() {
    return this.sum;
  }
  // getter : private 으로 접근이 막힌 변수의 값을 리턴해주는 메서드
  public float getAver() {
    return this.aver;
  }

  public String getName() {
    return this.name;
  }

  public int getKor() {
    return this.kor;
  }

  public void setKor(int kor) {
    if (kor < 0 | kor > 100) {
      return;
    }
    this.kor = kor;
    this.compute();
  }

  public int getEng() {
    return this.eng;
  }

  public void setEng(int eng) {
    if (eng < 0 | eng > 100) {
      return;
    }
    this.eng = eng;
    this.compute();
  }

  public int getMath() {
    return this.math;
  }

  public void setMath(int math) {
    if (math < 0 | math > 100) {
      return;
    }
    this.math = math;
    this.compute();
  }

}

 

반응형