When I run the code below, why does it throw this error?
Exception in thread "main" java.lang.CloneNotSupportedException: Student
at java.lang.Object.clone(Native Method)
at Student.clone(Student.java:44)
at StudentApp.main(StudentApp.java:10)
Here’s my main class:
public static void main(String[] args) throws CloneNotSupportedException {
Address address = new Address("湖南省长沙市林科大","1234567",20);
Student stu = new Student("诸葛亮量",20);
stu.setAddress(address);
Student stu2 = (Student)stu.clone();
stu2.setAddress(new Address("湖南省常德市区","484848348",22));
stu2.setName("张飞飞");
stu2.setAge(23);
stu.sayHi();
stu2.sayHi();
}
This is Student class:
public class Student{
private String name;
private int age;
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student() {
super();
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public void sayHi() {
System.out.println("大家好,我是" + this.getName() + "同学,我今年" + this.getAge()
+ "岁了……我的HashCode是:" + this.hashCode()+"。我家庭住址是"+address.getAddress()+",家庭住址的HashCode为:"+address.hashCode());
}
}
This is Address Class:
public class Address {
private String address;
private String tel;
private int roadNum;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public int getRoadNum() {
return roadNum;
}
public void setRoadNum(int roadNum) {
this.roadNum = roadNum;
}
public Address() {
super();
}
public Address(String address, String tel, int roadNum) {
super();
this.address = address;
this.tel = tel;
this.roadNum = roadNum;
}
}
From the javadoc
Have you tried to make your
Studentclass implement the Cloneable interface?