方法参数 java核心技术程序清单:4-4

public class ParamTest {

    public static void main(String[] args) {
        //测试方法1:不能改变一个基本数据类型的参数
        /*
        *通过定义一个基本数据类型,最为一个参数传入到函数中,
        *从运行结果上并没有改变,这里可以看出java是拷贝传值
        */
        System.out.println("Testing tripValue:");
        double percent = 10;
        System.out.println("Before: percent=" + percent);
        tripleValue(percent);
        System.out.println("After: percent="+percent);

        //测试方法2:方法可以改变一个对象的参数
        /*
        测试方法2通过新建一个对象,将这个对象的传到tripleSalary()方法中,本质是tripleSalary()将harry对象的引用拷贝一份,这样就有两个引用指向harry对象,第二引用调用public类型的raiseSalary()方法
        */
        System.out.println("\nTesting tripleSalary:");
        Employee harry = new Employee("Harry", 50000);
        System.out.println("Before: salary="+harry.getSalary());
        tripleSalary(harry);
        System.out.println("After: salary="+harry.getSalary());

        //测试方法3:一个方法不能让对象参数引用一个新的对象
        /*
        这个测试,是将新建的两个Employee对象的引用,将两个引用传入到swap()方法中。在swap()方法中,将拷贝的引用进行了交换,但最后两个引用并没有被返回,被丢弃了。
        */
        System.out.println("\nTesting swap:");
        Employee a = new Employee("Alice", 70000);
        Employee b = new Employee("Bob", 60000);
        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());
    }
    //将一个参数乘3
    public static void tripleValue(double x){
        x = 3 *x;
        System.out.println("End of method: x=" +x);
    }
    //员工的工资增加200%
    public static void tripleSalary(Employee x){
        x.raiseSalayr(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 raiseSalayr(double byPercent){
        double raise = salary * byPercent/100;
        salary += raise;
    }



}

运行结果

Testing tripValue:
Before: percent=10.0
End of method: x=30.0
After: percent=10.0

Testing tripleSalary:
Before: salary=50000.0
End of method: salary=150000.0
After: salary=150000.0

Testing swap:
Before: a=Alice
Before: b=Bob
End of method: x=Bob
End of method: y=Alice
After:a=Alice
After:b=Bob

你可能感兴趣的:(java)