Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- for
- react
- data structure
- Linux
- while
- python
- control
- php
- instruction
- function
- web
- javascript
- MIPS
- DATAPATH
- Pipelining
- Java
- Class
- architecture
- github
- computer
- DB
- html
- system
- CSS
- DS
- mysql
- Algorithm
- MacOS
- XML
- DoM
Archives
- Today
- Total
YYYEJI
[JAVA] Setter/Getter 메소드 본문
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을 통해 다시 값을 확인해보면 값이 잘 바뀐 것을 확인할 수 있습니다.
◡̈
'Java' 카테고리의 다른 글
[JAVA] Constructor란? (0) | 2022.12.27 |
---|---|
[JAVA] Class Type인 변수 할당하기 (0) | 2022.12.26 |
[JAVA] Pass by Value와 Pass by Reference의 차이점 (0) | 2022.12.26 |
[JAVA] Format parameter와 Actual parameter 이해하기 (0) | 2022.12.26 |
[JAVA] This와 Shadowed field 이해하기 (0) | 2022.12.26 |