> For the complete documentation index, see [llms.txt](https://docs.sysout.co.kr/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sysout.co.kr/base-language/java/advanced/method/getter-method.md).

# 반환(getter) 메소드

## 반환 메소드(getter method)

반환 메소드는 게터 메소드(getter method)라고 부르며 멤버 필드에 설정된 값을 반환하기 위해 사용한다. 필요하다면 값을 계산하여 반환하도록 만들 수도 있으며, 변수당 1개씩 만드는 것이 원칙이지만 다양한 활용법이 존재한다.

### 형태

`String name`에 대한 반환 메소드의 형태는 다음과 같다.

```java
String name;
public String getName(){
    return this.name;
}
```

`int score`에 대한 반환 메소드의 형태는 다음과 같다.

```java
int score;
public int getScore(){
    return this.score;
}
```

이름을 지을 때 `get`과 `score`를 합성하여 `getScore`라고 지으며, 반환값의 `this`는 생략이 가능하다.

### 데모 1 : 일반적인 클래스

```java
class Student{
    String name;
    int score;
    
    void setName(String name){
        this.name = name;
    }
    void setScore(int score){
        this.score = score;
    }
    String getName(){
        return this.name;
    }
    int getScore(){
        return this.score;
    }
}

public class GetterMethodExample01 {
    public static void main(String[] args){
        Student stu = new Student();
        stu.setName("피카츄");
        stu.setScore(80);
        System.out.println("이름 : " + stu.getName());
        System.out.println("점수 : " + stu.getScore());
    }
}
```

### 데모 2 : 계산을 수행하는 반환 메소드

```java
class Student {
    String name;
    int korean;
    int english;
    int math;
    
    void setName(String name){
        this.name = name;
    }
    void setKorean(int korean){
        this.korean = korean;
    }
    void setEnglish(int english){
        this.english = english;
    }
    void setMath(int math){
        this.math = math;
    }
    String getName(){
        return this.name;
    }
    int getKorean(){
        return this.korean;
    }
    int getEnglish(){
        return this.english;
    }
    int getMath(){
        return this.math;
    }
    
    int getTotal(){
        return this.korean + this.english + this.math;
    }
    double getAverage(){
        return this.getTotal() / 3.0;
    }
}

public class GetterMethodExample02 {
    public static void main(String[] args){
        Student stu = new Student();
        stu.setName("홍길동");
        stu.setKorean(100);
        stu.setEnglish(90);
        stu.setMath(85);
        
        System.out.println("총점 : "+stu.getTotal()+"점");
        System.out.println("합계 : "+stu.getAverage()+"점");
    }
}
```

위의 예제에서 `getTotal`, `getAverage`는 멤버 필드가 존재하지 않는데, 계산을 통해 값을 만들어내기 위하여 추가한 메소드이다. 이처럼 getter 메소드는 계산을 하여 값을 반환해야 하는 경우에도 사용할 수 있다.
