1. 程式人生 > >Java方法引數使用

Java方法引數使用

Java 中方法引數的使用情況:

•一個方法不能修改一個基本資料型別的引數 (即數值型或布林型)。

•一個方法可以改變一個物件引數的狀態。

•一個方法不能讓物件引數引用一個新的物件。

這三句話需要怎麼理解呢?下面用具體的例項來演示這個過程:

public class PramTest {
    public static void main(String[] args){
        
        //測試一
        double percent=10;
        System.out.println("Before:percent="+percent);
        tripleValue(percent);
        System.out.println("After:percent="+percent);
        System.out.println("*******************");
        
        //測試二
        Employee mike=new Employee("Mike",5000);
        System.out.println("Before:salary="+mike.getSalary());
        tripleSalary(mike);
        System.out.println("After:salary="+mike.getSalary());
        System.out.println("*******************");
        
        //測試三
        Employee a = new Employee("Alice",3000);
        Employee b = new Employee("Bob",7000);
        System.out.println("Before:a="+a.getName());
        System.out.println("Before:b="+b.getName());
        swap(a,b);
        System.out.println("After:a="+a.getName());
        System.out.println("After:b="+b.getName());
    }

    public static void tripleValue(double x){
        x = 3*x;
        System.out.println("End of method: x="+x);
    }

    public static void tripleSalary(Employee x){
        x.raiseSalary(200);
        System.out.println("End of method: salary="+x.getSalary());
    }

    public static void swap(Employee x,Employee y){

        Employee temp=x;
        x=y;
        y=temp;
        System.out.println("End of method: x="+x.getName());
        System.out.println("End of method: y="+y.getName());
    }

}
public class Employee {

    private String name;
    private double salary;

    public Employee(String n,double s){
        name = n;
        salary = s;
    }

    public String getName(){
        return name;
    }

    public double getSalary() {
        return salary;
    }

    public void raiseSalary(double byPercent){
        double raise = salary * byPercent/100;
        salary +=raise;
    }
}

執行結果: