38 참조
참조
그런데 자연의 산물이 아니라 거대한 약속의 집합인 소프트웨어의 세계에서 당연한 것은 없다. 이것이 당연하지 않은 이유는 다음 예제를 통해서 좀 더 분명하게 드러난다.
package org.opentutorials.javatutorials.reference; class A{ public int id; A(int id){ this.id = id; } } public class ReferenceDemo1 { public static void runValue(){ int a = 1; int b = a; b = 2; System.out.println("runValue, "+a); } public static void runReference(){ A a = new A(1); A b = a; b.id = 2; System.out.println("runReference, "+a.id); } public static void main(String[] args) { runValue(); runReference(); } }
차이점
결과
runValue, 1 runReference, 2
이 코드의 주인공은 아래와 같다.
b.id = 2; System.out.println("runReference, "+a.id);
놀라운 차이점이 있다. 변수 b에 담긴 인스턴스의 id 값을 2로 변경했을 뿐인데 a.id의 값도 2가 된 것이다. 이것은 변수 b와 변수 a에 담긴 인스턴스가 서로 같다는 것을 의미하다. 참조(reference)의 세계에 온 것을 환영한다.