Java浅谈clone

本文最后更新于:2 年前

default

主要是java浅克隆和深克隆的区别和实现。

(内容丢失)

Student对象(浅克隆)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package clone;

public class Student implements Cloneable {

public int id;
public String name;

public Student student;
//引用对象
public void sayName() {
System.out.println(this.name);
System.out.println(this.student.name);
}

//实现浅克隆
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}

public Student() {
// TODO Auto-generated constructor stub
}
public Student(String name) {
// TODO Auto-generated constructor stub
this.name = name;
}

public void setName(String name) {
this.name = name;
}
public void setStudent(Student student) {
this.student = student;
}
}


测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package clone;

public class StudentText {

public static void main(String[] args) throws CloneNotSupportedException {

Student a = new Student();
a.setName("张三");
//设置a的引用对象
a.setStudent(new Student("学孙1"));
System.out.println("学生a:");
a.sayName();

//浅克隆 a 对象为 b
Student b = (Student) a.clone();
System.out.println("学生b:");
b.sayName();
}
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!