05-04 값에 의한 호출과 객체에 의한 호출 - 개발새발 작성 일기

칼리와 초콜릿 공장·2023년 10월 28일
2

자바 개념

목록 보기
1/15

메서드에 값(원시 자료형)을 전달하는 것과 객체를 전달하는 것에는 큰 차이가 있다.
그 둘의 코드의 출력값을 비교해보면서 설명하겠다.

1. 원시 자료형을 전달하는 코드

class Updater {
    void update(int count) {
        count++;
    }
}

class Counter {
    int count = 0;  // 객체변수
}

public class Sample {
    public static void main(String[] args) {
        Counter myCounter = new Counter();
        System.out.println("before update: "+myCounter.count);
        Updater myUpdater = new Updater();
        myUpdater.update(myCounter.count);
        System.out.println("after update: "+myCounter.count);
    }
}

이 코드 값의 결과는 어떻게 나올 것 같은가?

before update: 0
after update: 0

myCounter.count의 값이 Updater 클래스의 update 메소드에 들어갔다 나왔지만 변화되지 않았다.
그 이유로는 예상했겠지만 int count와 같이 원시 자료형, 그저 값을 전달했기 때문이다.
update라는 메소드 안에서 count는 증가했지만 이 증가한 값은 어디에도 저장되지 않았다.

이는 C언어에서도 마찬가지이다.
좀 더 익숙한 C언어의 간단한 예시 코드를 들어 설명하자면

#include <stdio.h>

void ft_update(int a) {
    a++;
}

int main(void) {
    int a = 5;
    printf("before update: a = %d\n", a);
    ft_update(a);
    printf("after update: a = %d\n", a);

}

이의 결과값도

before update: 5
after update: 5

이와 같이 나온다.
반환값이 void라 연산된 값은 어디에도 저장되지 않는다.

그러면 이 변환된 값을 사용하고 싶을 때는 어떻게 코드를 바꿀 수 있는가

(1) 함수의 리턴값 int형으로 반환하여 저장

#include <stdio.h>

int ft_update(int a) {
    a++;
    return (a);
}

int main(void) {
    int a = 5;
    printf("before update: a = %d\n", a);
    a = ft_update(a);
    printf("after update: a = %d\n", a);

}

before update: 5
after update: 6

첫번째 방법으로는 int형 반환값을 만들어 a 변수에 증가된 값을 저장한다.

(2) 변수의 주소값을 참조하여 값 변경

#include <stdio.h>

void ft_update(int *pa) {
    (*pa)++;
    return ;
}

int main(void) {
    int a = 5;
    printf("before update: a = %d\n", a);
    ft_update(&a);
    printf("after update: a = %d\n", a);

}

before update: 5
after update: 6

두번째 방법으로는 한번 선언한 a를 다시 값을 저장해주고 싶지 않다면 포인터로 그에 대한 주소값을 참조해서 값을 바꿔준다 이 때는 반환할 필요가 없으므로 함수의 반환값은 void 여도 된다.

그러면 자바에서는 어떻게 값을 변환하는 가

2. 객체을 전달하는 코드

class Updater {
    void update (Counter counter) {
        counter.count++;
    }
}

class Counter {
    int count = 0;
}

public class SampleCounter {
    public static void main(String[] args) {
        Counter myCounter = new Counter();
        System.out.println("before : " + myCounter.count);
        Updater myUpdater = new Updater();
        myUpdater.update(myCounter);
        System.out.println("after : " + myCounter.count);
    }
}

before update: 0
after update: 1

이전 예제와의 차이점은 update 메서드의 입력 항목에 있다.
이전에는 int count와 같이 값을 전달받았다면 지금은 Counter counter와 같이 객체를 전달받도록 변경한 것이다.

profile
바삭하고 촉촉한 초코칩 쿠키

0개의 댓글

관련 채용 정보