1. 浅克隆实现
public class CloneTest {
public static void main(String[] args) throws CloneNotSupportedException {
Student s = new Student(18, new String("lhj"), new Hobby("ping-pang"));
Student s1 = s.clone();
System.out.println(s);
System.out.println(s1);
s1.age = 19;
s1.name = new String("lkj");
s1.hobby.hobby1 = new String("basketball");
System.out.println("修改后========");
System.out.println(s);
System.out.println(s1);
}
}
// 实现Cloneable接口
class Student implements Cloneable{
int age;
String name;
Hobby hobby;
Student(int age, String name, Hobby hobby){
this.age = age;
this.name = name;
this.hobby = hobby;
}
@Override
public Student clone() throws CloneNotSupportedException {
return (Student) super.clone(); // 调用父类的clone方法,直至调用Object.clone()方法实现对象的复制
}
@Override
public String toString() {
return "