clara_babybear
来源:互联网 发布:怎么安装解压软件 编辑:程序博客网 时间:2024/06/08 11:46
当一个对象被当作参数传递到一个方法后,此方法可改变这个对象的属性,并可返回变化后的结果,那么这里到底是值传递还是引用传递?
答:是值传递。java 编程语言只有值传递参数。当一个对象实例作为一个参数被传递到方法中时,参数的值就是该对象的引用一个副本。指向同一个对象,对象的内容可以在被调用的方法中改变,但对象的引用(不是引用的副本)是永远不会改变的。
java参数,不管是原始类型还是引用类型,传递的都是副本(有另外一种说法是传值,但是说传副本更好理解吧,传值通常是相对传址而言)。
如果参数类型是原始类型,那么传过来的就是这个参数的一个副本,也就是这个原始参数的值,这个跟之前所谈的传值是一样的。如果在函数中改变了副本的 值不会改变原始的值.
如果参数类型是引用类型,那么传过来的就是这个引用参数的副本,这个副本存放的是参数的地址。如果在函数中没有改变这个副本的地址,而是改变了地址中的 值,那么在函数内的改变会影响到传入的参数。如果在函数中改变了副本的地址,如new一个,那么副本就指向了一个新的地址,此时传入的参数还是指向原来的 地址,所以不会改变参数的值。
例:
1 public class paramtest {
2public static void main(string[] args){
3/**
4* test 1: methods can't modify numeric parameters
5*/
6system.out.println("testing triplevalue:");
7double percent = 10;
8system.out.println("before: percent=" + percent);
9triplevalue(percent);
10system.out.println("after: percent=" + percent);
11
12/**
13* test 2: methods can change the state of object parameters
14*/
15system.out.println("\ntesting triplesalary:");
16employee harry = new employee("harry", 50000);
17system.out.println("before: salary=" + harry.getsalary());
18triplesalary(harry);
19system.out.println("after: salary=" + harry.getsalary());
20
21/**
22* test 3: methods can't attach new objects to object parameters
23*/
24system.out.println("\ntesting swap:");
25employee a = new employee("alice", 70000);
26employee b = new employee("bob", 60000);
27system.out.println("before: a=" + a.getname());
28system.out.println("before: b=" + b.getname());
29swap(a, b);
30system.out.println("after: a=" + a.getname());
31system.out.println("after: b=" + b.getname());
32}
33
34private static void swap(employee x, employee y) {
35employee temp = x;
36x=y;
37y=temp;
38system.out.println("end of method: x=" + x.getname());
39system.out.println("end of method: y=" + y.getname());
40}
41
42private static void triplesalary(employee x) {
43x.raisesalary(200);
44system.out.println("end of method: salary=" + x.getsalary());
45}
46
47private static void triplevalue(double x) {
48x=3*x;
49system.out.println("end of method x= "+x);
50}
51 }
显示结果:
testing triplevalue:
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
======================================================
在最后,我邀请大家参加新浪APP,就是新浪免费送大家的一个空间,支持PHP+MySql,免费二级域名,免费域名绑定 这个是我邀请的地址,您通过这个链接注册即为我的好友,并获赠云豆500个,价值5元哦!短网址是http://t.cn/SXOiLh我创建的小站每天访客已经达到2000+了,每天挂广告赚50+元哦,呵呵,饭钱不愁了,\(^o^)/