java值传递

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值