package com.itcast.classes;
public class ZhiChuanDi {
/**
* java的所有参数传递都是值传递,不管基本类型还是引用类型
*/
public static void main(String[] args) {
int x = 100;
int y = 200;
//数值验证值传递
System.out.println("原始:" + x + "原始:" + y);
swap(x, y);
System.out.println("调用函数后:" + x + "调用函数后:" + y);
System.out.println();
//对象验证值传递
Person p1 = new Person("tom", "daxue");
Person p2 = new Person("kit", "zhongxue");
System.out.println("原始:" + p1.name + "原始:" + p2.name);
swap(p1, p2);
System.out.println("调用函数后:" + p1.name + "调用函数后:" + p2.name);
System.out.println();
//实现真正的改变数据
System.out.println("原始:" + p1.name + "原始:" + p2.name);
swap1(p1, p2);
System.out.println("调用函数后:" + p1.name + "调用函数后:" + p2.name);
}
//原始类型数据的值传递 实现不了数值的真正交换
public static void swap(int x, int y) {
int tmp = x;
x = y;
y = tmp;
System.out.println("函数内部交换后:" + x + "函数内部交换后:" + y);
}
//对象数据的值传递 实现不了对象的真正交换
public static void swap(Person x, Person y) {
Person tmp = x;
x = y;
y = tmp;
System.out.println("函数内部交换后:" + x.name + "函数内部交换后:" + y.name);
}
//对象的数据可以交换
public static void swap1(Person x, Person y) {
String tmp = x.getName();
x.name = y.getName();
y.setName(tmp);
System.out.println("函数内部交换后:" + x.name + "函数内部交换后:" + y.name);
}
}
class Person {
String name;
String school;
public Person(String name, String school) {
this.name = name;
this.school = school;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
}
详细解决方案
关于值传送的题
热度:55 发布时间:2016-04-23 22:00:15.0
相关解决方案