Java 引用传递

学了这么久的java,其实就明白有一个核心点,就是学会引用传递,你就觉得你明白java的精髓,就是来源于生活,面向生活。

值传递:(形式参数类型是基本数据类型):方法调用时,实际参数把它的值传递给对应的形式参数,形式参数只是用实际参数的值初始化自己的存储单元内容,是两个不同的存储单元,所以方法执行中形式参数值的改变不影响实际参数的值。

引用传递:(形式参数类型是引用数据类型参数):也称为传地址。方法调用时,实际参数是对象(或数组),这时实际参数与形式参数指向同一个地址,在方法执行中,对形式参数的操作实际上就是对实际参数的操作,这个结果在方法结束后被保留了下来,所以方法执行中形式参数的改变将会影响实际参数。

public class ParamTest {
public static void main(String[] args){

    /**
        * Test 1: Methods can't modify numeric parameters
        */
        System.out.println("Testing tripleValue:");
        double percent = 10;
        System.out.println("Before: percent=" + percent);
        tripleValue(percent);
       System.out.println("After: percent=" + percent);

       /**
        * Test 2: Methods can change the state of object parameters
        */
       System.out.println("\nTesting tripleSalary:");
       Employee harry = new Employee("Harry", 50000);
       System.out.println("Before: salary=" + harry.getSalary());
       tripleSalary(harry);
       System.out.println("After: salary=" + harry.getSalary());

       /**
        * Test 3: Methods can't attach new objects to object parameters
        */
       System.out.println("\nTesting swap:");
       Employee a = new Employee("Alice", 70000);
       Employee b = new Employee("Bob", 60000);
       System.out.println("Before: a=" + a.getName());
       System.out.println("Before: b=" + b.getName());
       swap(a, b);
       System.out.println("After: a=" + a.getName());
       System.out.println("After: b=" + b.getName());
 }

  private static void swap(Employee x, Employee y) {
     Employee temp = x;
     x=y;
     y=temp;
     System.out.println("End of method: x=" + x.getName());
     System.out.println("End of method: y=" + y.getName());
 }

private static void tripleSalary(Employee x) {
     x.raiseSalary(200);
     System.out.println("End of method: salary=" + x.getSalary());
}

   private static void tripleValue(double x) {
   x=3*x;
   System.out.println("End of Method X= "+x);
}

}
显示结果:
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

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值