java/객체지향 프로그래밍

call by value

appmaster 2019. 7. 10. 10:48
class Updater {
    public void update(Counter counter) {
        counter.count++;
    }
}

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

이렇게 메소드의 입력으로 객체를 전달받는 경우에는 메소드가 입력받은 객체를 그대로 사용하기 때문에 메소드가 객체의 속성값을 변경하면 메소드 수행 후 객체의 변경된 속성값이 유지되게 된다.

 

그대신 public void update(Counter counter)에서 대문자 Counter는 변하면 안된다. 왜냐하면 Counter클래스를 직접받는것이기 때문이다. 하지만 뒤에 counter는 변수의 이름이므로 아무거나 써도 상관이 없다. 그리고 counter.count++에 counter는 매개변수 Counter counter의 것이므로 만약 Counter x로 했다면 x.count++ 로 바꿔야한다.

'java > 객체지향 프로그래밍' 카테고리의 다른 글

Generic 제너릭  (0) 2019.07.19
자바 메소드(Method)  (0) 2019.07.10
자바 인터페이스(interface)  (0) 2019.04.16
자바 실제 객체  (0) 2019.04.16
자바 상속과 다형성  (0) 2019.04.16