java基础_传值与传址方法调用

本文通过一个Java示例程序深入探讨了基本类型与引用类型的参数传递区别。演示了当我们在方法中改变这些变量的值时,原始变量如何受到影响,并解释了背后的原因。
public class PassTest {
	public static void changeValue(int a) {
		a = 20;
	}

	public static void changeValue(Integer b) {
		b = 20;
	}

	public static void changeObjectRef(MyDate my) {
		my = new MyDate(2008, 10, 28);
	}

	public static void changeObjectAttr(MyDate my) {
		my.setDay(4);
	}

	public static void main(String[] args) {
		int a = 10;
		changeValue(a);
		System.out.println("a=" + a);

		Integer b = new Integer(10);
		changeValue(b);
		System.out.println("b=" + b);

		MyDate date;
		date = new MyDate(1964, 7, 22);
		changeObjectRef(date);
		System.out.println("date=" + date);
		changeObjectAttr(date);
		System.out.println("date=" + date);
	}
}

// MyDate类
class MyDate {
	private int year;
	private int month;
	private int day;

	MyDate(int year, int month, int day) {
		this.year = year;
		this.month = month;
		this.day = day;
	}

	public void setDay(int day) {
		this.day = day;
	}

	public String toString() {
		return this.year + "-" + this.month + "-" + this.day;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值