---
title: "JAVA中方法参数的引用传递"
author: "莫欺少年穷Java"
date: "2016-08-31T14:10:27Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2016-08-31T14:12:48Z"
id: 2321855
url: "https://hejiawangjava.iteye.com/blog/2321855"
---

“**当一个对象被当作参数传递到一个方法**”，这就是所谓的按引用传递。

 

```
public class User {
    
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
}
```

 

```
public class Test {
    
    public void set(User user){
        user.setName("hello world");
    }
    
    public static void main(String[] args) {
        
        Test test = new Test();
        User user = new User();
        test.set(user);
        System.out.println(user.getName());
    }
}
```

 上面代码的输出结果是“hello world”，这不必多说，那如果将set方法改为如下，结果会是多少呢？

```
 public void set(User user){
    user.setName("hello world"); 
    user = new User(); 
    user.setName("change"); 
  }
```

   答案依然是“hello world”，下面就让我们来分析一下如上代码。

 

 首先:

```
User user = new User();
```

   是在堆中创建了一个对象，并在栈中创建了一个引用，此引用指向该对象，如下图：

   
![](http://dl2.iteye.com/upload/attachment/0119/7170/7d440a41-044c-3a38-bf12-c354a3b4196b.png)  
 

 

```
test.set(user);
```

   是将引用user作为参数传递到set方法，注意：这里传递的并不是引用本身，而是一个引用的拷贝。也就是说这时有两个引用（引用和引用的拷贝）同时指向堆中的对象，如下图：

   
![](http://dl2.iteye.com/upload/attachment/0119/7172/8e9d4ee0-e89d-3cce-bdac-3e226d43bdf0.png)

```
user.setName("hello world");
```

   在set()方法中，“user引用的拷贝”操作堆中的User对象，给name属性设置字符串"hello world"。如下图：

   
![](http://dl2.iteye.com/upload/attachment/0119/7174/3614d2e5-1c7d-331c-83be-ef72cf0ea48f.png)

```
user = new User();
```

   在set()方法中，又创建了一个User对象，并将“user引用的拷贝”指向这个在堆中新创建的对象，如下图：

 

![](http://dl2.iteye.com/upload/attachment/0119/7176/849e03b1-300c-3b88-b572-75b59e86427f.png)

```
user.setName("change");
```

   在set()方法中，“user引用的拷贝”操作的是堆中新创建的User对象。

   
![](http://dl2.iteye.com/upload/attachment/0119/7178/852d2801-b02a-3e25-a3c1-83dfc17b0b5e.png)  
 

   set()方法执行完毕，目光再回到mian()方法

```
System.out.println(user.getName());
```

 因为之前，"user引用的拷贝"已经将堆中的User对象的name属性设置为了"hello world"，所以当main()方法中的user调用getName()时，打印的结果就是"hello world"。如下图：

　　  
![](http://dl2.iteye.com/upload/attachment/0119/7180/8363064e-6593-3805-996a-f7bbc405c411.png)