본문 바로가기
프로그래밍언어/Java

[Java] : private와 public에 대해서

by 오주현 2022. 1. 14.
반응형

private와 public

class NoteSetting {

    //노트 필드
    private int index = 0; //노트의 인덱스

    // 노트 인덱스를 올린다.
    public void upIndex(int value) {
        if (index + value > 200){
            index = 200;
        } else {
            index += value;
        }
        System.out.println("노트의 인덱스 번호는 " + getIndex() + "입니다.");
    }
		// 노트 인덱스를 줄인다.
    public void downIndex(int value) {
        if (index - value > 0){
            index = 0;
        } else {
            index -= value;
        }
        System.out.println("노트의 인덱스 번호는 " + getIndex() + "입니다.");
    }

    public int getIndex(){
        return index;
    }
}

NoteSetting 클래스에서 private 접근 제한자를 통해 index를 설정해 줬기 때문에 아래에 Note 클래스에서 index 변수에 대한 수정을 막을 수 있다.

public 접근 제한자를 통해 upIndex와 downIndex를 설정해 줬기 때문에 Note 클래스에서 upIndex()와 downIndex()를 통해 index 변수에 대한 수정을 할 수 있게 된다.

값 설정에 대한 함수는 NoteSetting에서 이루어진다.

public class Note{
    public static void main(String[]args){

        NoteSetting myNote3 = new NoteSetting();

        myNote3.upIndex(100);
        myNote3.upIndex(150);

        myNote3.downIndex(50);
        myNote3.downIndex(100);
    }
}

Note 클래스에서는 NoteSetting에서 지정된 private index에 직접적으로 접근, 수정이 불가능하기 때문에 NoteSetting에서 public로 지정된 upIndex()와 downIndex()를 통해 수정이 가능하게 된다.

즉, 변경 값을 해당 메서드로 넘겨주면 NoteSetting에서 값을 처리하게 된다.

반응형

댓글