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

一个普遍存在的误解是:java 中的参数以by reference 方式传递。这不是真的,参数其实是以by value 方式传递。这个误解源于[所有java objects 都是objects references]事实(关于object references 的详细信息,请见实践8)。如果你未能准确理解其中奥妙,则可能导致一些料想不到的后果。举个例子:

package fp;

import java.awt.Point;

public class Test
{
	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("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

感悟:p类似于c中的指针。

你可能感兴趣的:(java,c,object,String,Class,reference)