Java只有值传递,没有引用传递
什么是引用传递
我们先看一段引用传递(C++)的代码:有两个带参方法,分别对参数进行自增操作;
#include<iostream>
using namespace std;
//值传递
void change1(int n){
cout<<"值传递地址 "<<&n<<endl; //显示的是拷贝的地址而不是源地址
n++;
}
//引用传递
void change2(int &n){
cout<<"引用传递地址 "<<&n<<endl;
n++;
}
int main(){
int n=10;
cout<<"实参的地址 "<<&n<<endl;
change1(n);
cout<<"全局变量 n ="<<n<<endl;
change2(n);
cout<<"全局变量 n ="<<n<<endl;
return true;
}
调用值传递方法没有影响到全局变量,调用引用传递影响到了全局变量
实参的地址 0x7ffe0ffc043c
值传递地址 0x7ffe0ffc041c
全局变量 n =10
引用传递地址 0x7ffe0ffc043c
全局变量 n =11
java值传递方法
public class ServerInfo {
public static void add(int i){
++i;
System.out.println(i);
}
static int i=10;
public static void main(String[] args) {
System.out.println("---------this is main ---------" + i);
add(i);
System.out.println("---------this is main ---------" + i);
}
}
调用方法add,全局变量没有变化;
---------this is main ---------10
11
---------this is main ---------10
public class ServerInfo {
static int i=10;
public static void main(String[] args) {
System.out.println("---------this is main:------" + serverInfo);
testDemo(serverInfo);
System.out.println("---------this is main:------" + serverInfo);
}
private static ServerInfo serverInfo = null;
public static void testDemo(ServerInfo serverInfo) {
//传值
serverInfo = new ServerInfo();
serverInfo.i++;
System.out.println(serverInfo.i);
System.out.println(serverInfo);
}
}
结果
---------this is main:------null
11
com.asiainfo.a4.sgrp.ServerInfo@48140564
---------this is main:------null
------------------------ 全局变量 ------------------------------
public class ServerInfo {
Cat cat;
class Cat {
String name;
public Cat(String name) {
this.name = name;
}
}
public void testClass(Cat cat) {
this.cat = cat;
}
@Test
public void test() {
System.out.println("this is main ------- " + cat);
testClass(new Cat("Fat_Tiger"));
System.out.println("this is main ------- " + cat);
}
}
输出
this is main ------- null
this is main ------- com.asiainfo.a4.sgrp.ServerInfo$Cat@77f99a05