메서드 호출 시, 입력값으로 값을 전달하는 것과 객체를 전달하는 것의 차이가 있다.

 

 

 

값에 의한 호출

class Updater {
    void update(int count) {         → update라는 메서드를 생성 (입력값으로 정수값을 전달받음)
        count++;                            → 전달받은 값에 +1
    }
}

class Counter {    
    int count = 0;    →객체변수 생성
}

public class Day14 {
    public static void main(String[] args) {
        Counter myCounter = new Counter();    → Counter클래스의 인스턴스인 myCounter 생성
        System.out.println("before update:"+myCounter.count);      → myCounter객체의 객체변수값 호출 = 0
        Updater myUpdater = new Updater();      →Updater 클래스의 인스턴스인 myUpdater 생성                 
        myUpdater.update(myCounter.count);     →update메서드 호출 (입력값 myCounter.count = 0 )
        System.out.println("after update:"+myCounter.count);   
→ myCounter의 객체변수 자체를 넣은 것이 아닌 myCounter의 객체변수의 값만을 사용한 것이므로,
     myCounter.count값은 그대로 0

    }
}

 

>>실행결과 : 

before update:0

after update:0

 

 

객체에 의한 호출

class Updater {
    void update(Counter counter) {    → update라는 메서드를 생성 (입력값으로 객체 자체를 전달받음)
        counter.count++;                      → 객체의 객체변수값 자체를 +1 
    }
}

class Counter {
    int count = 0;    → 객체변수 생성
}
public class Day14 {
    public static void main(String[] args) {
        Counter myCounter = new Counter();    → Counter클래스의 인스턴스인 myCounter 생성
        System.out.println("before update:"+myCounter.count);      → myCounter객체의 객체변수값 호출 = 0
        Updater myUpdater = new Updater();      → Updater 클래스의 인스턴스인 myUpdater 생성                 
        myUpdater.update(myCounter);     → update메서드 호출 (입력값 myCounter)
        System.out.println("after update:"+myCounter.count); 
    }
}

 

>>실행결과 : 

before update:0

after update:1