当前位置:编程学习 > JAVA >>

Java中参数以by value方式而非by reference 方式传递(值传递)

Java中参数以by value方式而非by reference 方式传递(值传递)
       很多人都普遍的认为:java中的参数以by reference方式传递。其实这是一个误解,参数其实是以by value 方式传递。这个误解源于【Java object 都是 object reference 】这一事实。下面我们来看一个实例:
[java] view plaincopyprint?
<PRE class=java name="code"><SPAN style="FONT-SIZE: 14px">      import java.awt.Point; 
 
    public class PassByValue { 
 
    public static void modifyPoint(Point pt,int j){ 
        pt.setLocation(5, 5); 
        j=15; 
        System.out.println("During modifyPoint " + "pt = " + pt + " and j = " + j); 
    } 
 
    public static void main(String args[]){ 
        Point p = new Point(0, 0); 
        int i = 10; 
        System.out.println("Before modifyPoint " + "p = " + p + " and i = " + i); 
        modifyPoint(p, i); 
        System.out.println("Before modifyPoint " + "p = " + p + " and i = " + i); 
        } 
    }</SPAN></PRE> 
<PRE></PRE> 
<PRE></PRE> 
<PRE></PRE> 
<PRE></PRE> 

SPAN style="FONT-SIZE: 14px">      import java.awt.Point;        public class PassByValue {        public static void modifyPoint(Point pt,int j){          pt.setLocation(5, 5);          j=15;          System.out.println("During modifyPoint " + "pt = " + pt + " and j = " + j);      }        public static void main(String args[]){          Point p = new Point(0, 0);          int i = 10;          System.out.println("Before modifyPoint " + "p = " + p + " and i = " + i);          modifyPoint(p, i);          System.out.println("Before modifyPoint " + "p = " + p + " and i = " + i);          }      }</SPAN>        import java.awt.Point;

 public class PassByValue {

 public static void modifyPoint(Point pt,int j){
  pt.setLocation(5, 5);
  j=15;
  System.out.println("During modifyPoint " + "pt = " + pt + " and j = " + j);
 }

 public static void main(String args[]){
  Point p = new Point(0, 0);
  int i = 10;
  System.out.println("Before modifyPoint " + "p = " + p + " and i = " + i);
  modifyPoint(p, i);
  System.out.println("Before modifyPoint " + "p = " + p + " and i = " + i);
  }

 


 程序输出结果如下:


Before modifyPoint p = java.awt.Point[x=0,y=0] and i = 10
During modifyPoint pt = java.awt.Point[x=5,y=5] and j = 15
Before modifyPoint p = java.awt.Point[x=5,y=5] and i = 10

 

在此结果中整型的i值没有发生改变而Object类型的p的值却发生了变化,原因如下:
java 是通过值传递 当(by value传递) 当 调用modifyPoint()方法并传值的时候,
整型值i会被copy一个复件传到方法中,而p是Point 的对象,
所以出入的时候是将P的引用值(reference)的复件传递过去,而不是将Point 的复件传递过去。
当运行完,modifyPoint()方法中对i的值修改只是对它的副本进行修改,所以对main中的i值没有影响,
而modifyPoint()方法中对Point 的对象的引用值(reference)的副本的修改将改变main中的Point的引用值,
所以将影响main中p的值。

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,