- 参数传递分为:
1、按值调用:方法接收的是调用者提供的值。
2、 按引用调用:方法接收的是调用者提供的变量地址。 - java程序设计语言总是采用按值调用。也就是说,方法得到的是所有参数值的一个拷贝,特别是,方法不能修改传递给它的任何参数变量的内容。(方法结束之后,拷贝不再使用,被丢弃,改变拷贝的值不能改变原始参数变量的值)
- 方法参数共有两种类型:
- 基本数据类型(数字、布尔型)。
- 对象引用(可变、不可变) 。
- java中方法参数的使用情况:
(1)一个方法不能修改一个基本数据类型的参数(即数值型或布尔型)。
(2)一个方法可以改变一个对象参数的状态。
(3)一个方法不能让对象参数引用一个新的对象。
如下是一个Employee类,定义了它的姓名,薪水:
package weiyii;
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;
}
}
class ParamTest :
package weiyii;
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("\nTesting tripleSalary:");
Employee harry = new Employee("Harry",50000);
System.out.println("Before:salary="+harry.getSalary());
tripleSalary(harry);
System.out.println("After:salary="+harry.getSalary());
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());
***//方法并没有改变存储在xEmployee , yEmployee中对象的引用***
***//在方法结束之后拷贝被丢弃,原来的变量仍指向原来的对象***
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 mathod:y="+y.getName());
}
}