[Java-OOP3] Call by Value

이용준·2022년 10월 31일
0

Java

목록 보기
15/29

들어가기 전에

  • Call by value란, 값을 호출하는 것을 의미한다.
    • 전달받은 값을 복사해 처리한다.
    • 즉, 전달받은 값을 변경해도 원본이 변하지 않는다.
  • Call by reference
    • 주소를 전달하는 방식

메소드에 값(primitive type)을 전달하는 것과 객체(reference type)를 전달하는 것에는 큰 차이가 있다. 이는 매우 중요하므로 다시 한 번 알아보도록 하자.

메소드에 객체를 전달할 경우, 메소드에서 객체 변수 값을 변경할 수 있다.
다음 예제를 보자.

class Updater{
  void update(int count){
    count++;
  }
}
class Counter{
  int count = 0; //객체 변수
}  

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

위 예제는
1. updater 클래스는 전달받은 값을 1 증가시키는 update라는 메소드를 가지고 있다.
2. count라는 객체변수를 가진 Counter 클래스가 있다.
3. main 메소드는 Counter 클래스에 의해 생성된 객체변수(count)의 값을 Updater 클래스를 이용해 증가.
해당 과정을 담고 있다. 하지만 결과 값은 모두 0이 나온다.
그 이유는 udate 메소드는 값(int형)을 전달받았기 때문이다.

변경 후

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

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

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

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

update 메소드를 호출하는 부분도 다음처럼 변경되었다.

myUpdater.update(myCounter); 

이처럼 메소드의 입력으로 객체를 전달받는 경우에 입력 받은 객체를 그대로 사용하므로 객체의 속성값을 변경하면 메소드 수행 후에도 객체의 변경된 속성값이 유지된다.

profile
뚝딱뚝딱

0개의 댓글