标签:string类 private sys setname rgs his bsp stat new
1.基本类型是值传递
package com.gaopeng.springboot.test; public class PassTest { public static void main(String[] args) { int a = 1; // 传递基本数据类型,因为是将a的值传递给param,所以即便在pass函数中改变了 // 参数的值,a的值还是不会变。所以我们认为在传递基本数据类型的时候是值传递 pass(a); System.out.println("a= " + a); } private static void pass(int param) { param = 2; System.out.println("param= " + param); } }
运行结果:
param= 2
a= 1
2.对象封装是引用传递
package com.gaopeng.springboot.test; public class PassTest2 { public static void main(String[] args) { User user = new User(); user.setName("wutianqi"); // 传递对象,因为是将指向User的引用user传递给了param, // 在函数中param.setName会反应到真实的对象中去。因此我们 // 认为在这种情况下是引用传递 pass(user); System.out.println("my name is " + user.getName()); } private static void pass(User param) { param.setName("wuqi"); System.out.println("my name is " + param.getName()); } } class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
运行结果:
my name is wuqi
my name is wuqi
3.String类型可以看作是值传递
package com.gaopeng.springboot.test; public class PassTest3 { public static void main(String[] args) { String name = "wutianqi"; // 这里传递字符串参数,按照我们以前的观点这里应该传递的是将指向字符串的name引用 // 传递给param,那么在pass函数中修改参数的值会直接影响到name引用指向的字符串 // 的值,那么输出的结果依此应该是 my name is wuqi my name is wuqi pass(name); System.out.println("my name is " + name); } private static void pass(String param) { param = "wuqi"; System.out.println("my name is " + param); } }
运行结果:
my name is wuqi
my name is wutianqi
标签:string类 private sys setname rgs his bsp stat new
原文地址:https://www.cnblogs.com/gaopengpy/p/12053854.html