Java学习笔记之对象传值和引用总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32782771/article/details/52422367
<strong><span style="font-size:18px;">
public class Test {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Circle c1 = new Circle(1);
		Circle c2 = new Circle(2);
		
		swap1(c1,c2);
		System.out.println("After swap1 : c1 = " + c1.radius + " c2 = " + c2.radius);
		
		
		swap2(c1,c2);
		System.out.println("After swap2 : c1 = " + c1.radius + " c2 = " + c2.radius);
	}
	
	public static void swap1(Circle x,Circle y) {
		Circle temp = x;
		x = y;
		y = temp;
		System.out.println("After swap1 : x = " + x.radius + " y = " + y.radius);
	}
	
	public static void swap2(Circle x,Circle y) {
		double temp = x.radius;
		x.radius = y.radius;
		y.radius = temp;
	}
}

class Circle {
	double radius;
	
	Circle(double newRadius) {
		radius = newRadius;
	}
}</span></strong>
输出:
After swap1 : x = 2.0 y = 1.0
After swap1 : c1 = 1.0 c2 = 2.0

After swap2 : c1 = 2.0 c2 = 1.0

从swap1方法中输出中可以看到x和y对象确实是调换了,但在主方法中显示c1和c2是没有调换的,为什么呢?我们知道,想方法中传递对象实际传送的是对象的引用,也就是x是c1的引用,y是c2的引用,但是x和c1是不同的引用,因为引用也是一种数据类型,它们也有存放地址,因此x和y调换后,对c1和c2是没有影响的。

再来看看swap2方法,前面说了向方法传递对象时实际上是传递对象的引用,对象的数据域在方法中改变了,那么在main方法中原对象的数据域也自然就改变了。

再举一个简单例子:

import java.util.Date;

public class Test {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Date date = new Date(1234567);
		System.out.println("Before m1 : " + date);
		m1(date);
		System.out.println("After m1 : " + date);
	
	}
	
	public static void m1(Date date) {
		date = new Date(7654321);
	}
}
输出:

Before m1 : Thu Jan 01 08:20:34 GMT+08:00 1970
After m1 : Thu Jan 01 08:20:34 GMT+08:00 1970





猜你喜欢

转载自blog.csdn.net/qq_32782771/article/details/52422367
今日推荐