private: 같은 클래스 내부에서만 접근 가능 ( 외부 클래스, 상속 관계의 클래스에서도 접근 불가)- 아무것도 없음 (
default) : 같은 패키지 내부에서만 접근 가능 ( 상속 관계라도 패키지가 다르면 접근 불가)protected: 같은 패키지나 상속관계의 클래스에서 접근 가능하고 그 외 외부에서는 접근 할 수 없음public: 클래스의 외부 어디서나 접근 할 수 있음
private 으로 선언된 멤버 변수 (필드)에 대해 접근 및 수정할 수 있는 메서드를 public으로 제공get() 메서드만 제공 되는 경우 read-only 필드BirthDay.java
package ch10; public class BirthDay { private int day; private int month; private int year; private boolean isVaild; public int getDay() { return day; } public void setDay(int day) { this.day = day; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; if(month < 1 || month > 12) isVaild = false; else { isVaild = true; this.month = month; } } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public void showDate() { if(isVaild) System.out.println(year + "년" + month + "월" + day + "일 입니다."); else System.out.println("유효하지 않는 날짜입니다."); } }
BirthDayTest
package ch10; public class BirthDayTest { public static void main(String[] args) { BirthDay date = new BirthDay(); date.setYear(2019); date.setMonth(12); date.setDay(30); date.showDate(); } }
private나 protected로 정한다면, 그것은 객체의 정보를 숨김을 의미합니다.public void setMonth(int month) { this.month = month; if(month < 1 || month > 12) isVaild = false; else { isVaild = true; this.month = month; } }
private으로 제어한 멤버 변수도public메서드가 제공되면 접근 가능하지만 변수가public으로 공개되었을 때보다private일때 각 변수에 대한 제한을public메서드에서 제어 할 수 있다.- 객체 지향 프로그램에서 정보 은닉은 필요한 외부에서 접근 가능한 최소한의 정보를 오픈함으로써 객체의 오류를 방지하 클라이언트 객체가 더 효율적으로 객체를 활용할 수 있도록 해준다.
정보 은닉이 필요한 이유는?
- 객체들은 자신이 가지고 있는 것들을 모두 공개할 필요가 없기 때문입니다.
- 내부에서만 사용되는 필드와 메소드들은 외부로 공개하는 것이 의미가 없습니다.
- 다른 객체가 이들에 접근한다면, 피사용 객체의 안정성에 문제가 될 수도 있습니다.
- 공개가 불필요한 필드들이나 메소드들은 숨길 필요가 있습니다.