[Java] 참조 (2) (feat. 참조)

SeongEon Kim·2022년 6월 9일
0

JAVA

목록 보기
44/52
  1. 참조

아래 코드를 먼저 살펴보자.

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

a에 1을 대입하고, 1을 복제하여 b에 담았다.
변수 a와 변수 b의 데이터 타입은 A이다. 이때 인스턴스 A가 생긴다. b가 생성되면서 인스턴스 A를 가지고 있는 id 값을 b가 반응하여 이때 id값을 2라고 선언하면 2가 출력되는 것이다.
이를 참조 (reference)라고 한다.
변수 b에 담긴 인스턴스의 id 값을 2로 변경했을 뿐인데 a.id의 값도 2가 된 것이다. 이것은 변수 b와 변수 a에 담긴 인스턴스가 서로 같다는 것을 의미한다.

정리하자면, 참조는 id만을 공유하여 결국 최종 바꾼 것이 출력되고, 복제는 말 그대로 복제를 하는 것이기에 서로 독립적이다 라고 정리할 수 있다.

profile
꿈을 이루는 사람

0개의 댓글