java 对象入参是传入的是引用(一块内存), 基础类型是值(复制内容),测试代码如下
public class TestA { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
public class TestB { public void createTestA() { int id = 100; TestA testA = new TestA(); testA.setName("chenjun"); System.out.println("createTestA"); System.out.println(id); System.out.println(testA.getName()); altTestA(testA, id); System.out.println("after call altTestA"); System.out.println(id); System.out.println(testA.getName()); } public void altTestA(TestA testA, int id) { testA.setName("zhanglan"); id = 200; } public static void main(String[] args) { TestB test = new TestB(); test.createTestA(); } }
运行结果
createTestA
100
chen
after call altTestA
100
zhang