2015年9月14日 星期一

傳值呼叫

Java 傳值方式:Call by Value
針對基本數值:
int x = 3;
int y = x;
// x 將數值直接 copy 給 y

針對物件:
public class Demo {
    public static void main(String[] args){
    
        Employee x = new Employee();
        System.out.println("Salary: " + x.salary);
        foo(x);
        System.out.println("New Salary: " + x.salary);
    }

    // x -> e ,直接 copy 記憶體位址值
    public static void foo(Employee e) {
        //e = new Employee();
        e.setSalary(5000.00);
    }
}

class Employee {
    double salary = 1000.00;

    void setSalary(double d) {
        this.salary = d;
    }  
}