[JAVA] call by reference vs call by value
2021. 6. 30. 18:34ㆍ프로그래밍
메소드에 값을 전달하는 것이 아니라 객체를 전달하는 경우 메소드에서 객체의 객체변수 값을 변경할 수 있게 된다.
class Plus{
public void update(int count){
count++;
}
}
public class Counter{
int count = 0;
public static void main(){
Counter counter = new Counter();
Plus updater = new Plus();
updater.update(counter.count);
}
}
코드가 위와 같다면, count 값은 어떻게 나올까?
위와 같은 경우, Plus객체에서 update 메소드는 call by value로 값을 받았기때문에, count 값에는 변화가 없이 0으로 출력이 된다.
그렇다면 call by reference로 값을 받으려면 어떻게 받으면 될까?
class Plus{
public void update(Counter counter){
counter.count++;
}
}
public class Counter{
int count = 0;
public static void main(){
Counter counter = new Counter();
Plus updater = new Plus();
updater.update(counter);
}
}
위처럼 int를 담고있는 Counter 객체를 넘겨준 경우, Plus 객체의 update 메소드에서 count 값이 수정되어 Counter 객체의 count가 값이 변경되는 것을 알 수 있다.
'프로그래밍' 카테고리의 다른 글
윈도우 Alt키 <-> Ctrl command 키 위치 변경 - 윈도우 키보드 맥북처럼 사용하기 (6) | 2023.01.28 |
---|---|
[C++]2차원 배열 내장 STL 함수로 SORT하기 (0) | 2020.05.20 |