Java

[JAVA] Setter/Getter 메소드

YEJI ⍢ 2022. 12. 26. 22:39
728x90

Setter 란?

Setter은 accessor method라고 불리며, instance variable을 읽어주는 public method입니다.

 

 

getter 란?

Getter은 mutator method라고 불리며, instance variable을 수정해주는 public method입니다.

 

 

 

Setter/Getter는 왜 사용할까요?


객체의 변수(instance variable)를 객체 외부에서 직접적으로 접근하는 것을 막기 위해서 사용합니다.

객체의 외부에서는 method를 통해 변수에 접근하고 수정하도록 유도하고 있습니다.

 

 

 

예제를 살펴보기 위해 P class를 만들어줬습니다.


public class p {	
	private int width;
	private int height;
	
	public p() {         // constructor
		width = 100;
		height = 200;
	}
    
	public void setWidth(int width) {      // setter
		this.width = width;
	}
	
	public int getWidth() {      // getter
		return width;
	}
	
	public void setHeight(int height) {       // setter
		this.height = height;
	}
	
	public int getHeight() {      // getter
		return height;
	}
}

P class 안에 width, height라는 두 개의 instance variable있고 변수 각각마다 getter와 setter을 설정해줬습니다.

 

 

 

객체가 생성되면 instance 변수의 초기 설정은 width는 100, height는 200으로 셋팅됩니다.


public class main {
	public static void main(String[] args) {
		p area = new p();
		
		System.out.println("Width before Mutator: " + area.getWidth());
		System.out.println("Height before Mutator: " + area.getHeight());
		
		
		area.setWidth(1000);
		area.setHeight(2000);
		
		System.out.println();
		System.out.println("Width after Mutator: " + area.getWidth());
		System.out.println("Width after Mutator: " + area.getHeight());
	}
	
}

getter을 통해 값을 불러올 때 setter을 사용하기 전에는 객체가 생성될 때 초기화 됐던 값이 출력됩니다.

 

그 이후 setter을 통해 값을 변경시켜주고

 

getter을 통해 다시 값을 확인해보면 값이 잘 바뀐 것을 확인할 수 있습니다.

 

 

 

 

◡̈