java 方法调用,方法参数调用方式是值传递

  很多程序设计语言(特别是C++和Pasal)提供了两种参数传递的方式:值传递和引用调用。

在java程序设计语言中,对基本数据类型的参数是值传递,对象引用类型的参数是对象引用的值传递。总结一下就是值传递;

方法使用情况有以下三种:

  • 一个方法不能修改一个基本数据类型的参数(即数值型和布尔型)
  • 一个方法可以改变一个对象参数的状态
  • 一个方法不能实现让对象参数引用另一个新的对象
代码如下:
创建一个员工类
public class Employee {

  private String name;
  private double salary;
  private Date hireDay;

  public Employee(String n, double s, int year, int month, int day) {
    name = n;
    salary = s;
    GregorianCalendar date = new GregorianCalendar(year, month - 1, day);
    hireDay = date.getTime();
  }

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

  public String getName() {
    return name;
  }

  public double getSalary() {
    return salary;
  }

  public Date getHireDay() {
    return (Date) hireDay.clone();
  }

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

}

再创建一个测试类
public class ParamTest {

  public static void main(String[] args) {
    //测试一方法不能修改一个基本类型的参数
    System.out.println("testing tripleValue:");
    double percent = 10;
    System.out.println("Before: percent=" + percent);
    tripleValue(percent);
    System.out.println("After: percent=" + percent);
    //一个方法可以改变一个对象参数的状态
    System.out.println("testing tripleSalary:");
    Employee employee = new Employee("王某某",120000);
    System.out.println("Before: salary=" + employee.getSalary());
    tripleSalary(employee);
    System.out.println("After: salary=" + employee.getSalary());
    //一个方法不能实现让对象参数引用一个新的对象
    Employee employee1 = new Employee("张三",3000);
    Employee employee2 = new Employee("李四",6000);
    System.out.println("testing swap:");
    System.out.println("Before: employee1=" + employee1.getName());
    System.out.println("Before: employee2=" + employee2.getName());
    swap(employee1,employee2);
    System.out.println("After: employee1=" + employee1.getName());
    System.out.println("After: employee2=" + employee2.getName());

  }

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

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

  public static void swap(Employee x, Employee y) {
    Employee temp = x;
    x = y;
    y = temp;
    System.out.println("end method:x=" + x.getName());
    System.out.println("end method:y=" + y.getName());
  }

}

执行结果:
testing tripleValue:
Before: percent=10.0
end method:x=30.0
After: percent=10.0
testing tripleSalary:
Before: salary=120000.0
end method:salary=360000.0
After: salary=360000.0
testing swap:
Before: employee1=张三
Before: employee2=李四
end method:x=李四
end method:y=张三
After: employee1=张三
After: employee2=李四

你可能感兴趣的:(Java技术)