Skip to content

Commit 1a9e99c

Browse files
committed
对象采用的不是引用调用,实际上,对象引用是按 值传递的。
1 parent 7bca90d commit 1a9e99c

3 files changed

Lines changed: 85 additions & 0 deletions

File tree

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @program JavaBooks
3+
* @description: Student
4+
* @author: mf
5+
* @create: 2020/02/07 22:01
6+
*/
7+
8+
package com.transfer;
9+
10+
public class Student {
11+
12+
private String name;
13+
14+
public Student(String name) {
15+
this.name = name;
16+
}
17+
18+
public String getName() {
19+
return name;
20+
}
21+
22+
public void setName(String name) {
23+
this.name = name;
24+
}
25+
26+
@Override
27+
public String toString() {
28+
return "Student{" +
29+
"name='" + name + '\'' +
30+
'}';
31+
}
32+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @program JavaBooks
3+
* @description: TransferDemo2
4+
* @author: mf
5+
* @create: 2020/02/07 22:04
6+
*/
7+
8+
package com.transfer;
9+
10+
public class TransferDemo2 {
11+
12+
public static void main(String[] args) {
13+
int[] arr = { 1, 2, 3, 4, 5 };
14+
System.out.println(arr[0]);
15+
change(arr);
16+
System.out.println(arr[0]);
17+
// 法得到的是对象引用的拷贝,对象引用及其他的拷贝同时引用同一个对象。
18+
}
19+
20+
private static void change(int[] array) {
21+
// 修改数组中的一个元素
22+
array[0] = 0;
23+
}
24+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @program JavaBooks
3+
* @description: TransferDemo3
4+
* @author: mf
5+
* @create: 2020/02/07 22:05
6+
*/
7+
8+
package com.transfer;
9+
10+
public class TransferDemo3 {
11+
public static void main(String[] args) {
12+
// 有些程序员(甚至本书的作者)认为 Java 程序设计语言对对象采用的是引用调用,实际上,这种理解是不对的。
13+
Student s1 = new Student("Mai");
14+
Student s2 = new Student("Feng");
15+
swap2(s1, s2);
16+
System.out.println("s1:" + s1.getName());
17+
System.out.println("s2:" + s2.getName());
18+
// 方法并没有改变存储在变量 s1 和 s2 中的对象引用。
19+
// swap 方法的参数 x 和 y 被初始化为两个对象引用的拷贝,这个方法交换的是这两个拷贝
20+
}
21+
22+
private static void swap2(Student x, Student y) {
23+
Student temp = x;
24+
x = y;
25+
y = temp;
26+
System.out.println("x:" + x.getName());
27+
System.out.println("y:" + y.getName());
28+
}
29+
}

0 commit comments

Comments
 (0)