본문 바로가기

자바 기초

자바 접근제어자, public, private - Do it ! 자바프로그래밍기초

객체 지향 프로그래밍에서는 예약어를 사용해 클래스 내부의 변수나 메서드, 생성자에 대한 접근 권한을 지정할 수 있다.

이러한 예약어를 접근 제어자라고 한다.

 

public이라고 선언한 변수나 메서드는 외부 클래스에서 접근이 가능하며 외부 클래스가 사용할 수 있다는 뜻

private으로 선언한 변수나 메서드는 외부 클래스에서 사용할 수 없다. 

 

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;
    }
}
public class StudentTest {
	public static void main(String[] args) {
    	Student studentLee = new Student();
        studentLee.studnetName = "이상원";
        
        System.out.println(studentLee.getStudentName());
    }
}

Student 클래스에서 studentName을 private로 지정했기 때문에

StudentTest 클래스에서 studentLee.studentName = "이상원"; 은 오류가 발생한다.

접근 제어자가 public 이라면 외부 클래스에서도 이 변수에 접근할 수 있지만, private는 외부 접근이 제한되기 때문이다.

 

private으로 선언한 studentName 변수를 외부 클래스에서 사용하려면 어떻게 해야할까?

studentName 변수를 사용할 수 있도록 public  메서드를 제공해야 한다. 

studentName 에 접근할 수 있는 메서드가 get(), set() 메서드이다.

 

public class StudentTest {
	public static void main(String[] args) {
    Student studentLee = new Student();
    studentLee.setStudentName("이상원");
    
    System.out.println(studentLee.getStudentName());
}

이렇게 studentName 멤버 변수에 이름을 직접 대입하는 것이 아니고 setStudentName() 메서드를 활용해서 값을 대입할 수 있다.

 

 

변수를 public으로 선언하는 것과, private으로 선언하고 나서 그 변수를 사용할 수 있도록 public 메서드를 제공하는 것은 무슨 차이가 있을까?

클래스의 멤버 변수를 public으로 선언하면 접근이 제한되지 않으므로 정보의 오류가 발생할 수 있다. 이런 경우에는 오류가 나면 그 값이 해당 변수에 대입되지 못하도록 다음과 같이 변수를 private으로 바꾸고 public 메서드를 별도로 제공해야 한다.

이처럼 클래스 내부에서 사용할 변수나 메서드는 private으로 선언해서 외부에서 접근하지 못하도록 하는 것을 객체 지향에서는 '정보 은닉' 이라고 한다.

즉 모든 변수를 private으로 선언해야 하는 것은 아니지만, 필요한 경우에는 private으로 선언하여 오류를 막을 수 있다.

 

public : 외부 클래스 어디에서나 접근 가능

protected : 같은 패키지 내부와 상속 관계의 클래스에서만 접근할 수 있고, 그 외 클래스에서는 접근 불가

private : 같은 클래스 내부에서만 접근할 수 있다.

아무것도 없는 경우 :  default이며 같은 패키지 내부에서만 접근할 수 있다.

 

public class MyDate {
	public int day;
    public int month;
    public int year;
}
public class MyDateTest {
	public static void main(String[] args) {
    	MyDate date = new MyDate();
        date.month = 2;
        date.day = 31;
        date. year = 2018;
    }
}

이 경우 2월은 28일까지 밖에 없는데 31일이 입렫되면 정보에 오류가 생긴다. (윤년 고려 X)

 

public class MyDate {
	private int day;
    private int month;
    private int year;
    
    public setDay(int Day) {
    if (month == 2) {
    	if (day < 1 || day > 28) {
        	System.out.println("오류입니다.");
        }
        else {
        	this.day = day;
        }
    }
}

이렇게 set() 메서드를 활용해 코드를 구현하면 정보의 오류를 방지할 수도 있다.