Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Tags more
Archives
Today
Total
관리 메뉴

David의 블로그

[JAVA]정보 오류를 막을 수 있는 정보 은닉, 접근제어자 본문

프로그래밍/Java

[JAVA]정보 오류를 막을 수 있는 정보 은닉, 접근제어자

David 리 2023. 10. 30. 23:55

접근제어자

JAVA에서 객체 지향 프로그램에서는 예약어를 통해 메소드, 변수, 생성자에 접근할 때 접근 권한을 지정할 수 있습니다.

흔히들 접근제어자 'public'을 많이 씁니다.

여기서 정보은닉과 관련있는 private에 대해 다루어 볼려고 합니다.

정보은닉은 외부에서 내부 데이터를 가공하거나 들여다볼 수 없는 특성을 의미합니다.

소스를 통해 살펴보겠습니다.

 

 

||예시

getStudentName , setStudentName 메소드,

내부변수 studentID, studentName, grade, address정보가 있는 Student 클래스입니다.

public class Student {

        int studentID;
        private String studentName;
        int grade;
        String address;

        public String getStudentName() {
            return studentName;
        }

        public void setStudentName(String studentName) {
            this.studentName = studentName;
        }

    }

 

Student 클래스를 실행 할 메인클래스 StudentTest입니다.

public class StudentTest {

    public static void main(String[] args) {
        Student studentLee = new Student();
        studentLee.studentName = "David";           //오류
//        studentLee.setStudentName("David");

        System.out.println(studentLee.getStudentName());
    }
}

메인클래스에서 

Student형의 studentLee라는 객체를 생성하고

studentLee.studentName = "David"라고 할당해주는 부분에서 에러가 나고있습니다.

바로 private라는 접근제어자의 특성때문인데,

같은 클래스내의 접근은 허용하지만,

다른 클래스내에서는 접근을 허용하지 않습니다.

 

 

||해결

그렇다면 접근을 어떻게 해야하나?

바로 getter, setter메소드를 이용하는 방법이 있습니다.

public class Student {

        int studentID;
        private String studentName;
        int grade;
        String address;


        // getter
        public String getStudentName() {
            return studentName;
        }

        //setter
        public void setStudentName(String studentName) {
            this.studentName = studentName;
        }

    }
public class StudentTest {

    public static void main(String[] args) {
        Student studentLee = new Student();
        //studentLee.studentName = "David";
        studentLee.setStudentName("David");                     // setter를 통해 값 할당.

        System.out.println(studentLee.getStudentName());        // getter메소드 호출. 정상실행
    }
}

 

이 처럼, 세터를 통해 값을 할당하고 

불러올 때 게터를 이용합니다.