[Java] 참조 (4) (feat. 메소드의 매개변수와 참조)

SeongEon Kim·2022년 6월 9일
0

JAVA

목록 보기
46/52
package org.opentutorials.javatutorials.reference;
 
public class ReferenceParameterDemo {
     
    static void _value(int b){
        b = 2;
    }
     
    public static void runValue(){
        int a = 1;
        _value(a);
        System.out.println("runValue, "+a);
    }
     
    static void _reference1(A b){
        b = new A(2);
    }
     
    public static void runReference1(){
        A a = new A(1);
        _reference1(a);
        System.out.println("runReference1, "+a.id);     
    }
     
    static void _reference2(A b){
        b.id = 2;
    }
 
    public static void runReference2(){
        A a = new A(1);
        _reference2(a);
        System.out.println("runReference2, "+a.id);     
    }
     
    public static void main(String[] args) {
        runValue(); // runValue, 1
        runReference1(); // runReference1, 1
        runReference2(); // runReference2, 2
    }
 
}

위 코드의 결과는 아래와 같다.

runValue, 1

메소드 value의 인자로 a를 전달했다. 인자 a는 매개변수 b가 되어서 value 안으로 전달되고 있다. value 안에서 b의 값을 변경했다. value가 실행된 후에 runValue에서 a값을 출력해본 결과 값이 변경되지 않았다. 호출된 메소드의 작업이 호출한 메소드에 영향을 미치지 않고 있다.

runReference1, 1

메소드 reference1 안에서 매개변수 b의 값을 다른 객체로 변경하고 있다. 이것은 지역변수인 b의 데이터를 교체한 것일 뿐이기 때문에 runReference1의 결과에는 영향을 미치지 않는다.

runReference2, 2

위의 코드는 호출된 메소드의 작업이 호출한 메소드의 변수에 영향을 미친다. 매개변수 b의 값을 다른 객체로 교체한 것이 아니라 매개변수 b의 인스턴스 변수 id 값을 2로 변경하고 있다. 이러한 맥락에서 reference2의 변수 b는 runReference2의 변수 a와 참조 관계로 연결되어 있는 것이기 때문에 a와 b는 모두 같은 객체를 참조하고 있는 변수다.

profile
꿈을 이루는 사람

0개의 댓글