欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

值传递和引用传递

程序员文章站 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]