使用原型模式,实现对学生类的浅克隆,学生类包括姓名,年龄,专业,学院,学校等数据,学生类实现Cloneable接口,重写父类的clone()方法,使用父类Object的clone()方法,复制一个和原型对象一样的学生对象。
时间: 2024-06-14 10:06:05 浏览: 173
```java
class Student implements Cloneable {
private String name;
private int age;
private String major;
private String college;
private String school;
public Student(String name, int age, String major, String college, String school) {
this.name = name;
this.age = age;
this.major = major;
this.college = college;
this.school = school;
}
// Getter and Setter methods
@Override
public Student clone() throws CloneNotSupportedException {
return (Student) super.clone();
}
}
// Usage
Student originalStudent = new Student("John", 20, "Computer Science", "Engineering", "ABC University");
try {
Student clonedStudent = originalStudent.clone();
// Now you have a cloned student object which is the same as the original student object
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
```
阅读全文