值传递和引用传递
程序员文章站
2022-06-07 16:46:10
...
public class Test {
public static void main(String[] args) {
UserA u = new UserA("AAA", 1);
Test t = new Test();
System.out.println("初始 : " + u);
t.test(u);
System.out.println("最终 : " + u);
}
public void test(UserA userA) {
System.out.println("入参 userA : " + userA);
userA.setName("ooooo");
userA = new UserA("xxxxxxxxxxx", 99);
System.out.println("出参 userA : " + userA);
}
}
class UserA {
private String name;
private int age;
public UserA() {
}
public UserA(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "UserA[name=" + name + ", age = " + age + "]";
}
}
执行结果:
初始 : UserA[name=AAA, age = 1]
入参 userA : UserA[name=AAA, age = 1]
出参 userA : UserA[name=xxxxxxxxxxx, age = 99]
最终 : UserA[name=ooooo, age = 1]
public static void main(String[] args) {
UserA u = new UserA("AAA", 1);
Test t = new Test();
System.out.println("初始 : " + u);
t.test(u);
System.out.println("最终 : " + u);
}
public void test(UserA userA) {
System.out.println("入参 userA : " + userA);
userA.setName("ooooo");
userA = new UserA("xxxxxxxxxxx", 99);
System.out.println("出参 userA : " + userA);
}
}
class UserA {
private String name;
private int age;
public UserA() {
}
public UserA(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "UserA[name=" + name + ", age = " + age + "]";
}
}
执行结果:
初始 : UserA[name=AAA, age = 1]
入参 userA : UserA[name=AAA, age = 1]
出参 userA : UserA[name=xxxxxxxxxxx, age = 99]
最终 : UserA[name=ooooo, age = 1]