☕Java 접근 제어자, 정보 은닉, getter setter

hamsang·2022년 5월 14일
0

Java

목록 보기
8/36
post-thumbnail

☕ 접근 제어자

접근 제어자설명
public외부 클래스 어디서나 접근할 수 있다.
protected같은 패키지 내부와 상속 관계의 클래스에서만 접근할 수 있고 그 외 클래스에서는 접근할 수 없다.
아무것도 없는 경우default이며 같은 패키지 내부에서만 접근할 수 있다.
private같은 클래스 내부에서만 접근할 수 있다.

☕ 정보 은닉(information hiding)

  • 객체지향에서 클래스 내부에서 사용할 변수나 메서드를 private으로 선언해 외부에서 접근하지 못하도록 하는 것

📍 get(), set() 메서드 사용하기

  • 이클립스 get(), set() 자동 생성 단축키 : Alt + Shift + s
package hiding;

public class Student {
	
	int studentID;
	private String studentName; //studentName을 private으로 선언
    
    
    public String getStudentName() {
		return studentName;
	} //private 변수인 studentName에 접근해 값을 가져오는(출력하는) public get() 메서드
    
	public void setStudentName(String studentName) {
		this.studentName = studentName; 
	} //private 변수인 studentName에 접근해 값을 지정하는(대입하는) public get() 메서드
	
package hiding;

public class StudentTest {
	public static void main(String[] args) {
		Student studentLee = new Student();
		
        //studentLee.studentName = "이하린"; 코드는 오류 발생.
        // private 변수인 studentName에 바로 접근을 시도했기 때문이다.
        
		studentLee.setStudentName("이하린");
        //setStudentName() 메서드를 활용해 private 변수에 접근 가능
		
		System.out.println(studentLee.getStudentName());
	}

}

studentName 멤버 변수에 이름 값을 직접 대입하는 것이 아니고 setStudentName() 메서드를 활용하여 값을 대입할 수 있다. 즉 외부 클래스에서 private 변수에 직접 접근할 수는 없지만, public 메서드를 통하면 private 변수에 접근할 수 있다.

profile
햄생

0개의 댓글

관련 채용 정보