62,614
社区成员
发帖
与我相关
我的任务
分享
public class Test {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = s1.clone();
System.out.println(s1.age);
System.out.println(s2.age);
}
}
class Student implements Cloneable {
//覆盖了 clone 方法实现了克隆功能的类必须实现 Cloneable 这一标记接口
public int age = 18;
//此处应有一个clone()方法
public Student clone() {
//首先覆盖超类 Object 提供的 clone 方法,然后扩大它的访问级别(由 protected 到 public)
//然后将方法返回值类型具体化,这个也叫方法返回值协变
Student s = null;
try {
s = (Student) super.clone();
} catch (CloneNotSupportedException e) {
//正常情况下此异常不可能发生
}
return s;
}
}