美文网首页
Practical Java: 一般技术

Practical Java: 一般技术

作者: Gino_Gu | 来源:发表于2017-02-13 21:24 被阅读0次

实践1:参数以by value方式而非by reference方式传递

Java中的参数以by value方式传递,举个例子:

import java.awt.Point;
class PassByValue
{
  public static void modifyPoint(Point pt, int j)
  {
    pt.setLocation(5,5);                                      //1
    j = 15;
    System.out.println("During modifyPoint " + "pt = " + pt + " and j = " + j);
  }

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

以上代码的输出为

程序输出

main函数中的基本数据类型i的值在调用modifyPoint后并没被改变,可见传给参数j的是i的一份副本。但是对象p的值被修改了,说明pt拿到的是指向point对象实例的引用的一份副本,p和pt指向的是同一个对象,它看起来像这样

1486993181952.jpg

因此在调用 pt.setLocation(5,5); //1 后,该Point对象被修改了。

相关文章

网友评论

      本文标题:Practical Java: 一般技术

      本文链接:https://www.haomeiwen.com/subject/ljvtwttx.html