java方法参数传递的结果

java方法参数传递的结果

1.方法中基本数据类型作为参数,形参值的改变不会影响实参的值。

2.方法中对象类型作为参数,形参值的改变影响到实参的值。

3.方法中对象类型作为参数,形参引用的改变不会影响到实参的引用。

 1 public class Employee {
 2     private String name;
 3     
 4     public String getName() {
 5         return name;
 6     }
 7 
 8     public void setName(String name) {
 9         this.name = name;
10     }
11 
12     public Employee() {
13     }
14     
15     public Employee(String n) {
16         this.name=n;
17     }
18     
19     public static void swap(Employee x,Employee y) {
20         Employee tmp = new Employee();
21         tmp=x;
22         x=y;
23         y=tmp;
24     }
25     
26     public static void setBasic(int x) {
27         x += 100;
28     }
29     
30     public static void setObj(Employee x) {
31         x.setName("newName");
32     }
33     
34     public static void main(String[] args) {
35         
36         int i=1;
37         
38         Employee.setBasic(i);            //int i为基本数据类型作为参数,形参值的改变不会影响实参的值。
39         System.out.println("i=" + i);    //i=1
40         
41         Employee a=new Employee("a");
42         Employee b=new Employee("b");
43         
44         Employee.setObj(a);                //a对象类型作为参数,形参值的改变影响到实参的值。
45         System.out.println("a.name=" + a.getName());    //a.name=newName
46         
47         Employee.swap(a, b);            //a,b对象类型作为参数,形参引用的改变不会影响到实参的引用。
48         
49         System.out.println("a.name=" + a.getName() + ",b.name=" + b.getName()); //a.name=newName,b.name=b
50         
51         
52     }
53 }

猜你喜欢

转载自www.cnblogs.com/labing/p/12544167.html