当前位置: 移动技术网 > IT编程>开发语言>Java > Java值传递和引用传递详解

Java值传递和引用传递详解

2019年07月22日  | 移动技术网IT编程  | 我要评论

当一个对象被当作参数传递到一个方法后,此方法可改变这个对象的属性,并可返回变化后的结果,那么这里到底是值传递还是引用传递?
答:是值传递。java 编程语言只有值传递参数。当一个对象实例作为一个参数被传递到方法中时,参数的值就是该对象的引用一个副本。指向同一个对象,对象的内容可以在被调用的方法中改变,但对象的引用(不是引用的副本)是永远不会改变的。

java参数,不管是原始类型还是引用类型,传递的都是副本(有另外一种说法是传值,但是说传副本更好理解吧,传值通常是相对传址而言)。

如果参数类型是原始类型,那么传过来的就是这个参数的一个副本,也就是这个原始参数的值,这个跟之前所谈的传值是一样的。如果在函数中改变了副本的值不会改变原始的值。

如果参数类型是引用类型,那么传过来的就是这个引用参数的副本,这个副本存放的是参数的地址。如果在函数中没有改变这个副本的地址,而是改变了地址中的 值,那么在函数内的改变会影响到传入的参数。如果在函数中改变了副本的地址,如new一个,那么副本就指向了一个新的地址,此时传入的参数还是指向原来的 地址,所以不会改变参数的值。

例:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网