Practical Java: 一般技术

实践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对象被修改了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容