您的位置:首页 > 编程语言 > Java开发

JAVA的值调用

2017-04-17 20:02 134 查看
值调用表示方法接受的是调用者提供的值。

引用调用表示方法接收的是调用者提供的变量地址。

JAVA程序设计语言总是采用值调用,即方法得到的是所有参数值的一个拷贝,特别是方法不能修改传递给他的任何变量参数变量的内容。

参考下面示例:

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 tripSalary:");
Employee harry = new Employee("Harry",50000);
System.out.println("Before: salary=" +harry.getSalary());
tripSalary(harry);
System.out.println("After:salary=" +harry.getSalary());

System.out.println("\nTesting swap:");
Employee a = new Employee("Alice",70000);
Employee b = new Employee("Bob",80000);
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 tripSalary(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());
}
}
class Employee
{
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;
}
private String name;
private double salary;
}


运行结果:

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

Testing tripSalary:
Before: salary=50000.0
End of method: Salary=100000.0
After:salary=100000.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程序设计语言中,方法参数的使用情况:

一个方法不能修改一个基本数据类型的参数(即数值型和布尔型)

一个方法可以改变一个对象参数的状态。

一个方法不能实现让对象参数引用一个新的对象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 值调用